Table of Contents Cover image Front matter Copyright Preface Chapter 1. The Art of Programming Mechanics 1.1. Introduction 1.2. Programming on the Right Side of the Brain 1.3. Creating Art from the Left Side of the Brain 1.4. How Game Engines Work 1.5. A Scripting Primer 1.6. A Game Art Asset Primer 1.7. Summary Chapter 2. Real-World Mechanics 2.1. Introduction 2.2. Principles of Vectors 2.3. Defining 2D and 3D Space 2.4. Two-Dimensional Games in a 3D Game Engine 2.5. The Laws of Physics 2.6. Physics and the Principles of Animation 2.7. Two-Dimensional and 3D Tricks for Optimizing Game Space 2.8. Summary Chapter 3. Animation Mechanics 3.1. Introduction 3.2. Sprites 3.3. Texture Atlas 3.4. Animated Sprites 3.5. Baked 3D Animations 3.6. Biomechanics 3.7. Animation Management 3.8. Secondary Animation 3.9. Summary Chapter 4. Game Rules and Mechanics 4.1. Introduction 4.2. Game Mechanics
4.3. Primary Mechanics 4.4. Developing with Some Simple Game Mechanics 4.5. Rewards and Penalties 4.6. Summary Chapter 5. Character Mechanics 5.1. Introduction 5.2. Line of Sight 5.3. Graph Theory 5.4. Waypoints 5.5. Finite State Machines 5.6. Flocking 5.7. Decision Trees 5.8. Fuzzy Logic 5.9. Genetic Algorithms 5.10. Cellular Automata 5.11. Summary Chapter 6. Player Mechanics 6.1. Introduction 6.2. Game Structure 6.3. Principles of Game Interface Design 6.4. Inventories 6.5. Teleportation 6.6. Summary Chapter 7. Environmental Mechanics 7.1. Introduction 7.2. Map Design Fundamentals 7.3. Terrain 7.4. Camera Tricks 7.5. Skies 7.6. Weather 7.7. Particles 7.8. Summary Chapter 8. Mechanics for External Forces 8.1. Introduction 8.2. Up and Running on a Mobile Device 8.3. Integrating Haptics and External Motion into Games
8.4. Accessing Mobile Hardware Features 8.5. The Social Mechanic 8.6. Platform Deployment: App Store, Android Market, and Consoles 8.7. Summary Index
Front matter Holistic Game Development with Unity
Holistic Game Development with Unity
An All-in-One Guide to Implementing Game Mechanics, Art, Design, and Programming Penny de Byl
AMSTERDAM • BOSTON • HEIDELBERG • LONDON NEW YORK • OXFORD • PARIS • SAN DIEGO
SAN FRANCISCO • SINGAPORE • SYDNEY • TOKYO Focal Press is an imprint of Elsevier
Copyright Focal Press is an imprint of Elsevier 225 Wyman Street, Waltham, MA 02451, USA The Boulevard, Langford Lane, Kidlington, Oxford, OX5 1GB, UK © 2012 Elsevier, Inc. All rights reserved. No part of this publication may be reproduced or transmitted in any form or by any means, electronic or mechanical, including photocopying, recording, or any information storage and retrieval system, without permission in writing from the publisher. Details on how to seek permission, further information about the Publisher's permissions policies and our arrangements with organizations such as the Copyright Clearance Center and the Copyright Licensing Agency, can be found at our website: www.elsevier.com/permissions. This book and the individual contributions contained in it are protected under copyright by the Publisher (other than as may be noted herein). Notices Knowledge and best practice in this field are constantly changing. As new research and experience broaden our understanding, changes in research methods, professional practices, or medical treatment may become necessary. Practitioners and researchers must always rely on their own experience and knowledge in evaluating and using any information, methods, compounds, or experiments described herein. In using such information or methods they should be mindful of their own safety and the safety of others, including parties for whom they have a professional responsibility. To the fullest extent of the law, neither the Publisher nor the authors, contributors, or editors, assume any liability for any injury and/or damage to persons or property as a matter of product liability, negligence or otherwise, or from any use or operation of any methods, products, instructions, or ideas contained in the material herein. Library of Congress Cataloging-in-Publication Data Application submitted British Library Cataloguing-in-Publication Data A catalogue record for this book is available from the British Library.
ISBN: 978-0-240-81933-4 For information on all Focal Press publications visit our website at www.elsevierdirect.com 1112131454321 Printed in the United States of America
Preface
About This Book I decided to write this book when I found existing literature for budding game designers, artists, and programmers tended to focus on only one specific vein of games development—that being a design, artistic, or programming book. Those with artistic talents and ideas for games could not find a good resource to ease them into programming. However, programming texts tend to be dry and ignore the visual aspect. With the face of the game development industry rapidly changing from a small number of large development teams to much more of a cottage industry consisting of small multiskilled teams, it is more imperative that individuals are skilled in both art and programming. Game development tools are also not what they used to be, and rapid game development tools such as Unity are making it a possibility for individuals to make complete games from scratch. To address these issues, this book is written for the artist who wants to program and the programmer who wants some pointers about using game art. In the beginning I started writing just for artists but soon came to realize the content was equally as relevant to those wanting to learn how to start programming games.
How This Book Is Organized This book has been written with artists who want to learn how to develop games and programmers who want to learn about using art in games in mind. It approaches game development in a unique combination of teaching programming, keeping in mind the design; for programming, a game's graphical user interface is entirely different from making it look good. Learning about how design impacts on programming and vice versa is a logical way to introduce both sides of the game develop coin to game creation. All chapters focus on sets of mechanical functions existing within games: •Chapter One, The Art of Programming Game Mechanics, explains the roles both art and programming play in creating games and explores the limitations of having one without the other. In addition, the complementary nature of digital art and programming is established. •Chapter Two, Real-World Mechanics, examines the branch of physics dealing with the study of motion. Motion is a fundamental idea in all of science that transcends the computer screen into virtual environments. This chapter examines kinematics, which describe motion, and dynamics, which examine the causes of motion with respect to their use in computer games. It introduces the physical properties of the real world and demonstrates how a fundamental understanding of mathematics, physics, and design principles is critical in any game environment. Composition, rules of animation, and design principles are introduced in parallel with technical considerations, mathematics, and programming code, which controls and defines the movement of characters, cameras, environments, and other game objects. •Chapter Three, Animation Mechanics, studies the technical nature of 2D and 3D animated models. The reader will develop skills with respect to the programmatic control of their own artwork, models, and/or supplied assets in a game environment. Elementary mathematics, physics, and programming concepts are introduced that demonstrate the concepts of keyframes, animation states, and development of dynamic character movement and sprite animation. •Chapter Four, Game Rules and Mechanics, introduces common generic game mechanics such as matching, sorting, managing, and hitting. Examples of how each of these is represented visually in a game and the programming that controls them are explained in depth. Common algorithms and data structures used for each mechanic are worked through with the reader integrating, where appropriate, key art assets. •Chapter Five, Character Mechanics, explains simple artificial intelligence algorithms to assist the reader in creating his or her own believable nonplayer characters. Animation states and techniques covered in Chapter 3 are integrated with game-specific data structures and algorithms to control the behavior of characters from flocking of birds to opponents that follow and interact with the player. •Chapter Six, Player Mechanics, presents the code and artwork deployed to develop graphical user interfaces
and maintain player states. It includes details about the development of inventory systems, heads-up displays, and character–environment interaction. •Chapter Seven, Environmental Mechanics, reveals the fundamental concepts in creating and optimizing game environments. It covers techniques from adding detail to environments to make them more believable to tricks for working with large maps and weather simulations. •Chapter Eight, Mechanics for External Forces, examines issues related to developing games while keeping in mind the new plethora of input devices, social data, GPS locators, motion sensors, augmented reality, and screen sizes. Included is practical advice on using Unity to deploy games to iPhone, iPad, and Android mobile devices that leverage touch screens, accelerometers, and networking.
The Companion Web Site The Web site accompanying this book is http://www.holistic3d.com. It contains all the files referred to in the workshops, finished examples, and other teaching and learning resources.
Acknowledgments First I thank my editor, Sara Scott, who has kept my project on track. Her encouragement and enthusiasm in the book have been highly motivational. In addition, thanks must go to Mark Ripley of Effervescing Elephant Interactive who acted as technical editor and provided valuable insight on game programming with Unity. Next, I acknowledge Unity3d who have developed a truly inspirational game development tool and all the forum contributors who have freely shared their ideas and code to answer all conceivable game development questions. The forums at http://forums.unity3d.com are an invaluable knowledge base. Finally, I thank my family, Daniel, Tabytha, Deefa (Labrador 15 years old), and Merlin (Labrador < 1 year old). Daniel has been an absolute rock. His knowledge of Microsoft Word formatting still leaves me amazed, and his proofreading and testing of all the workshops have saved so much time (i.e., if the code in this book doesn't work for you—blame him! ). Tabytha has been as patient as a 6–7-year-old can be when it seems your mother's every waking moment is spent in front of the iMac. As always, Deefa has provided moral support, sitting constantly under the desk at my feet, and Merlin, the little voice in the back of my mind, wondering which pair of shoes he was dining on given his obvious absence from the room. To me, game development is the quintessential seam where the tectonic plates of programming and art meet. It is where both domains really start to make sense. If you are reading this, I hope you feel the same.
Chapter 1. The Art of Programming Mechanics Everyone can be taught to sculpt: Michelangelo would have had to be taught how not to. So it is with the great programmers. Alan Perlis In 1979, art teac her B etty E dwards publis hed the ac c laim ed Draw ing on the Right S ide of the B rain. T he es s enc e of the text taught readers to draw what they s aw rather than what they thought they s aw. T he hum an brain is s o adept at tas ks s uc h as pattern rec ognition that we internally s ym bolize prac tic ally everything we s ee and regurgitate thes e patterns when as ked to draw them on paper. Children do this very well. T he s im plic ity in a c hild's drawing s tem s from their internal repres entation for an objec t. A s k them to draw a hous e and a dog and you'll get s om ething you and they c an rec ognize as a hous e and dog or, m ore ac c urately, the ic on for a hous e and dog, but s om ething far from what an ac tual hous e and dog look like. Keywords: point, line, s hape, direc tion, s ize, texture, c olor, gam e engine, logic
1.1. Introduction In 1979, art teacher Betty Edwards published the acclaimed Drawing on the Right Side of the Brain. The essence of the text taught readers to draw what they saw rather than what they thought they saw. The human brain is so adept at tasks such as pattern recognition that we internally symbolize practically everything we see and regurgitate these patterns when asked to draw them on paper. Children do this very well. The simplicity in children's drawing stems from their internal representation for an object. Ask them to draw a house and a dog and you'll get something you and they can recognize as a house and dog or, more accurately, the icon for a house and dog, but something far from what an actual house and dog look like. This is evident in the child's drawing in Figure 1.1. The title of the book, Drawing on the Right Side of the Brain, also suggests that the ability to draw should be summoned from the side of the brain traditionally associated with creativity and that most bad drawings could be blamed on the left.
Fig 1.1 Dogs in the yard of a castle by Tabytha de Byl aged 4.
Different intellectual capability is commonly attributed to either the left or the right hemispheres. The left side being responsible for the processing of language, mathematics, numbers, logic, and other such computational activities, whereas the right deals with shapes, patterns, spatial acuity, images, dreaming, and creative pursuits. From these beliefs, those who are adept at computer programming are classified as left-brained and artists as right-brained. The segregation of these abilities to either side of the brain is called lateralization. While lateralization has been generally accepted and even used to classify and separate students into learning style groups, it is a common misconception that intellectual functioning can be separated so clearly. In fact, the clearly defined left and right brain functions are a neuromyth stemming from the overgeneralization and literal isolation of the brain hemispheres. While some functions tend to reside more in one side of the brain than the other, many tasks, to some degree, require both sides. For example, many numerical computation and language activities require both hemispheres. Furthermore, the side of the brain being utilized for specific tasks can vary among people. Studies have revealed that 97% of right-handed people use their left hemisphere for language and speech processing and 70% of left-handed people use their right hemisphere. In short, simply classifying programmers as left brainers and artists as right brainers is a misnomer. This also leads to the disturbing misconception that programmers are poor at art skills and that artists would have difficulty understanding programming. Programming is so often generalized as a logical process and art as a creative process that some find it inconceivable that programmers could be effective as artists and vice versa. When Betty Edwards suggests that people should use their right brain for drawing it is in concept, not physiology. The location of the neurons the reader is being asked to use to find their creative self is not relevant. What is important is that Dr. Edwards is asking us to see drawing in a different light—in a way we may not have considered before. Instead of drawing our internalized symbol of an object that has been stored away in the brain, she asks us to draw what we see. To forget what we think it looks like. In the end this symbolizes a switch in thinking away from logic and patterns to images and visual processing. There is no doubt that some people are naturally better at programming and others at art. However, by taking Edwards' anyone can draw attitude, we can also say anyone can program. It just requires a little practice and a change of attitude.
1.2. Programming on the Right Side of the Brain While it is true that pure logic is at the very heart of all computer programs, it still requires an enormous amount of creativity to order the logic into a program. The process is improved greatly when programmers can visualize the results of their code before it even runs. You may liken this to a scene from The Matrix where the characters look at screens of vertically flowing green numbers and text but can visualize the structure and goings on in a photorealistic, three-dimensional virtual reality. To become a good computer programmer you need to know the language of the code and be able to visualize how it is affecting the computer's memory and the results of running the program. Learning a computer language is one key to being able to program. However, understanding how the language interacts with the computer to produce its output is even more important. Good programmers will agree that it is easy to switch between programming languages once you have mastered one. The fundamental concepts in each are the same. In some languages, such as C, C++, C#, Javascript, Java, and PhP, even the text and layout look the same. The basic code from each aforementioned language to print Hello World on the computer screen is shown in listings 1.1 through 1.6. Listing 1.1.C #include < stdio.h> main() { printf("Hello World"); }
Listing 1.2.C++ #include < iostream > using namespace std; void main() { cout < < "Hello World" < < endl; }
Listing 1.3.C# public class HelloWorld { public static void Main() { System.Console.WriteLine("Hello World"); } }
Listing 1.4.JavaScript (in Bold) Embedded in HTML < html> < head> < title > Hello World < body> < script type = "text/javascript"> document.write(‘Hello World’);