Learning 2D Game Development With Unity

3y ago
35 Views
6 Downloads
1.77 MB
77 Pages
Last View : 1m ago
Last Download : 3m ago
Upload by : Casen Newsome
Transcription

Learning 2D GameDevelopmentwith Unity

Addison-Wesley Learning SeriesVisit informit.com/learningseries for a complete list of available publications.The Addison-Wesley Learning Series is a collection of hands-on programming guides that help you quickly learn a new technology or language so youcan apply what you’ve learned right away.Each title comes with sample code for the application or applications built inthe text. This code is fully annotated and can be reused in your own projectswith no strings attached. Many chapters end with a series of exercises toencourage you to reexamine what you have just learned, and to tweak oradjust the code as a way of learning.Titles in this series take a simple approach: they get you going right away andleave you with the ability to walk off and build your own application and applythe language or technology to whatever you are working on.

Learning 2D GameDevelopmentwith Unity A Hands-On Guideto Game CreationMatthew JohnsonJames A. HenleyUpper Saddle River, NJ Boston Indianapolis San FranciscoNew York Toronto Montreal London Munich Paris MadridCapetown Sydney Tokyo Singapore Mexico City

Many of the designations used by manufacturers and sellers to distinguish their products are claimedas trademarks. Where those designations appear in this book, and the publisher was aware of atrademark claim, the designations have been printed with initial capital letters or in all capitals.The authors and publisher have taken care in the preparation of this book, but make no expressedor implied warranty of any kind and assume no responsibility for errors or omissions. No liability isassumed for incidental or consequential damages in connection with or arising out of the use of theinformation or programs contained herein.For information about buying this title in bulk quantities, or for special sales opportunities (whichmay include electronic versions; custom cover designs; and content particular to your business,training goals, marketing focus, or branding interests), please contact our corporate sales departmentat corpsales@pearsoned.com or (800) 382-3419.For government sales inquiries, please contact governmentsales@pearsoned.com.For questions about sales outside the United States, please contact international@pearsoned.com.Visit us on the Web: informit.com/awLibrary of Congress Cataloging-in-Publication DataJohnson, Matthew (Computer programmer)Learning 2D game development with Unity : a hands-on guide to game creation / Matthew Johnson,James A. Henley.pages cmIncludes index.ISBN 978-0-321-95772-6 (pbk. : alk. paper)—ISBN 0-321-95772-5 (pbk. : alk. paper)1. Computer games—Programming. 2. Unity (electronic resource) I. Henley, James A. II. Title.QA76.76.C672J64 2015794.8'1526—dc232014037406Copyright 2015 Pearson Education, Inc.All rights reserved. Printed in the United States of America. This publication is protected by copyright,and permission must be obtained from the publisher prior to any prohibited reproduction, storage in aretrieval system, or transmission in any form or by any means, electronic, mechanical, photocopying,recording, or likewise. To obtain permission to use material from this work, please submit a writtenrequest to Pearson Education, Inc., Permissions Department, One Lake Street, Upper Saddle River, NewJersey 07458, or you may fax your request to (201) 236-3290.Unity, Unity Free, Unity Pro, and the Unity Web Player are registered trademarks of Unity Technologies.Adobe , Flash , and Photoshop are registered trademarks or trademarks of Adobe SystemsIncorporated in the United States and/or other countries. THIS PRODUCT IS NOT ENDORSED ORSPONSORED BY ADOBE SYSTEMS INCORPORATED, PUBLISHER OF Adobe Flash and Photoshop .The Kenney logo and the Made with Kenney Logo belong to Kenney.nl, Netherlands, used withpermission.Mac is a trademark of Apple Inc., registered in the U.S. and other countries.Linux is the registered trademark of Linus Torvalds in the U.S. and other countries.DirectX, Direct3D, and Visual Studio are either registered trademarks or trademarks of MicrosoftCorporation in the United States and/or other countries.ISBN-13: 978-0-321-95772-6ISBN-10: 0-321-95772-5Text printed in the United States on recycled paper at RR Donnelley in Crawfordsville, Indiana.First printing, December 2014Editor-in-ChiefMark L. TaubExecutive EditorLaura LewinDevelopment EditorSonglin QiuManaging EditorJohn FullerSenior ProductionEditorKesel WilsonCopy EditorBarbara WoodIndexerJack LewisProofreaderMelissa PanagosTechnical ReviewersReshat Hasankolli, IISheetanshu SinhaEditorial AssistantOlivia BasegioCover DesignerChuti PrasertsithCompositorShepherd, Inc.

vFirst and foremost, a big thanks to my friends and familyfor supporting me throughout this process. You pushed meto start this book and then begged me to finish it!To my late father, who taught me to inspireand entertain others with my talent andwild imagination: I am forever your biggest fan.Last, to the love of my life and best friend, Jessica:without you this book would have been justmore dust in the wind of my ideas. Thank you forall of your guidance and wisdom, and for believingthat I could accomplish this. I love you always and forever.—Matthew JohnsonFor my wonderful wife, who brought me teawhenever I locked myself in my office to writeand tolerated being temporarily widowed by this book.—James A. Henleyv

This page intentionally left blank

Contents at a GlanceContents at a GlancePreface   xixAcknowledgments   xxvAbout the Authors   xxviiIntroduction   11 Setting Up the Unity Development Environment   92 Understanding Asset Creation   273 Creating 2D Sprites   414 Building the Game World   535 The Basics of Movement and Player Control   716 Adding Animations to Our Scene   957 Setting Up Player Physics and Colliders   1198 Creating and Applying Gameplay Systems   1359 Creating Hazards and Crafting Difficulty   15910 Creating the Menus and Interface Elements   19311 Applying Effects to the GameObjects   21512 Organization and Optimization   24713 Bringing It All Together   26914 UGUI   291Appendix: JavaScript Code Samples   301Index   323vii

This page intentionally left blank

ContentsContentsPreface   xixAcknowledgments   xxvAbout the Authors   xxviiIntroduction   1Introduction to Unity   1Downloading and Installing Unity   1Project Wizard   4Open Project Tab   4Create New Project Tab   5Packages   5Setting Our Project   6Project Structure   6Folder Organization   7File Naming Conventions   71 Setting Up the Unity Development Environment   9Welcome Screen   9The Unity Interface   10Menus   10Toolbar   19Hierarchy   20Inspector   20Project Browser   21Scene View   23Game View   24Summary   25Exercises   252 Understanding Asset Creation   27File Formats   273D Formats   272D Formats   28ix

xContentsImporting Our Assets   28Importing from Inside Unity   28Importing Premade Assets from the File Browser   29Creating New Assets   29Importing Packages   31Unity Packages   31Custom Packages   31GameObjects   33Our First GameObject   33Creating a GameObject   34Components   36Creating a Component   37Assign a Component   37Prefabs   38Summary   39Exercises   393 Creating 2D Sprites   41Working in 2D   412D Behaviors   412D Workspace   42Building Our Sprites   43Import Settings   43Pixels To Units   45Sprite Editor   45Sprite Packing   48Packing Tag   48Sprite Packer   48Additional Sprite Packing Resources   49Summary   50Exercises   504 Building the Game World   53Level Design 101   53Setting the Scene   53Creating a Roadmap   54Adding Details   55

ContentsGetting around Our Scene   56Scene Gizmo   56Perspective versus Isometric   57Camera Controls   57Manipulating Objects in Unity   59Transform Tools   59Z-Depth   61Settings   62Our First Level   64Positioning GameObjects Manually   64Using the Snap Settings to Position GameObjects   64Using Grid Snapping to Position GameObjects   64Efficient Level Design   66Adding Sorting Elements   67Continuing On   69Summary   69Exercises   705 The Basics of Movement and Player Control   71Coding in Unity3D   71The Three Languages   71Choosing the “Right” Language   72Making the Player Go   72Different Ways of Handling Movement   72Creating and Hooking Up Our PlayerController   74Setting Up a Basic Follow-Cam   83Introducing the Input Manager   83Error Handling and Debugging   85Handling Exceptions   85Try-Catch-Finally—Gracefully Handling Exceptions   87Debug.Log() Is Your Friend   89Using Breakpoints to Halt Code Execution   90Summary   93Exercises   94xi

xiiContents6 Adding Animations to Our Scene   95Some Rules for Animation   95Animation Principles   952D versus 3D Animation   96Transform versus Frame Animation   97Scripted Animations   98Imported Animations   98Creating Animations   99Animation Component   100Animation Clip   100Animation Window   101Animation Events   107Animation States   108Animator Controller   108Animator Component   109Animator Window   110Editing the Player Controller   112Working with the State Machine   115Transitions   115Any State   115Blend Trees   116Summary   116Exercises   1177 Setting Up Player Physics and Colliders   119Understanding Physics   119Mass   119Gravity   120Force   1202D versus 3D   1206DoF   120Z-Depth   121Rotations   121Physics 2D Settings   122General Physics Settings   122Layer Collision Matrix   123Rigidbodies   124

ContentsColliders   125Circle Collider   126Box Collider   126Edge Collider   126Polygon Collider   126Physics Materials   128Constraints   129Summary   134Exercise   1348 Creating and Applying Gameplay Systems   135Trigger Volumes in Unity   135Trigger2D Functions   135Adding Trigger Components to GameObjects   136Creating Checkpoints   136Scripting the Checkpoint Component   137Sizing and Placing Our Checkpoint Trigger   138Using Checkpoints with Respawn   140Preparing the Pit Trigger Volume   140Scripting the Pit Trigger Component   140Creating Collectibles   144Preparing the Floating Coin Prefabs for Collection   145Scripting the CoinPickup Component   145Preparing the Popped Coin Prefabs for Collection   147Preparing the Coin Box Prefabs   147Scripting the Coin Box Component   150Scripting the CoinSpawner Component   152Hooking It All Together   153A Touch of Polish   154Tracking the Player’s Stats   155Summary   157Exercises   1589 Creating Hazards and Crafting Difficulty   159Creating Your First Enemy   159Preparing the Slime Enemy GameObject   159Inheritance and the EnemyController Component   161xiii

xivContentsScripting the Enemy Slime Component   162Adding Walls to the Level   164Handling Collision with Other Slimes   165Adding Animation to the Slime   166Dealing Damage   167Scripting Damage into the PlayerStatsComponent   167Creating the Damage Trigger   168Passing through the Player’s Space   170Adding Damage to the Pits   172Adding Temporary Immunity Post-Damage   172Visually Representing Immunity, the ClassicalWay   175Handling Player Death   177Expanding on Platforming   178Preparing the Moving Platform Prefab   179Scripting the Flight Points Component   180Creating Your Second Enemy   182Preparing the Fly Enemy GameObject   183Adding Animation to the Fly   184Scripting the FlyController Component   185Adjusting the FlightPoints Script   185Maintaining Your Enemy Arrangements   187Preparing the Spawn Trigger   188Scripting the Spawn Trigger Component   189A Few Words on Challenge   190Summary   191Exercises   19110 Creating the Menus and Interface Elements   193UI Design   193Diegetic   194Non-diegetic   194Meta   194Spatial   194Unity Native GUI   194GUI Style   195GUI Skin   195

ContentsGUI Controls   195Compound Controls   197GUI Class   197GUI Layouts   197GUI Text   198GUI Texture   198Creating a Splash Screen   198Title Screen   200Game Over Screen   201Game Win Screen   202HUD   204Creating the Visuals   204Creating the Scripts   206Summary   212Exercise   21311 Applying Effects to the GameObjects   215Introducing the Shuriken Particle System   215Terms to Know   215Creating a Particle System   216Modules and Properties of a Particle System   217Base Particle System Properties   217Other Particle System Modules   218Particle System Curves   219Adding Particle Effects to the Game   220Creating a Particle Effect for Coin Boxes   220Hooking Up the Coin Box Particle Effect   223Creating a Particle Effect for Damage   223Calling the Damage Particle System from Code   225Having a Little Particle Fun   227Unity’s Audio System   227The Audio Source Component   228The Audio Listener Component   230The Audio Reverb Zone Component   230Adding Sound to the Player   231Adding Footsteps to the Walk Cycle   231xv

xviContentsAdding Sound to the Jump Event   233Adding Sound to the Damage Event   234Adding Sound to the Collectible System   236Applying Sound to the Coin Box   236Applying Sound to Coin Collection   237Applying Some Extra Polish   238Cleaning Up the Camera   238Cleaning Up Player Death   241Summary   246Exercises   24612 Organization and Optimization   247Organizing Assets   247Organizing Our Prefabs   248Labels   249Hierarchy   250Organizing Scripts and Code   253Organizing the Script Files   253Organizing the Code   254Optimizations   261Prefabs   262Physics   262Draw Calls   264Triangle Count   265Batching   266Rendering Statistics Window   266Summary   267Exercises   26813 Bringing It All Together   269Tying the Levels Together   269Preparing the Victory Trigger Prefab   269Creating the Victory Trigger Script   272Retrieving the Coin Value   274Hooking Up the Intro Screens   275Win or Lose: Getting Back into the Action   277Recovering from Game Over   278Starting Over from a Win   279

ContentsBuilding and Deploying the Game   281Web Player’s Build Settings   282PC, Mac, and Linux Standalone Build Settings   282Cross-Platform Player Settings   283Web Player’s Player Settings   283The Right Settings for the Job   284Building the Game for the Web Player   285Deploying the Game to the Web   285Post-Deployment   286Moving Forward   286Polish Considerations   286Monetization   287Final Words   29014 UGUI   291UGUI Components   291Creating Our Example Interface   293Canvas Component   293Rect Transform   296UI Rect Tool   298Adding the Mask   299The Event System and Event Triggers   299Summary   300Appendix: JavaScript Code Samples   301Player Scripts   301Collectible Scripts   307Enemy Scripts   309Game System Scripts   310GUI Scripts   314Hazard Scripts   320System Scripts   322Index   323xvii

This page intentionally left blank

PrefaceWhy Write This Book?Since there are hundreds of books on game design and quite a few about using theUnity game engine, you might be asking, “Why even write another book on Unity?”We wanted to write a book about game development with a 2D approach, using anengine that is most widely known for being 3D. There are a bunch of Unity bookscovering 3D mesh and building game worlds, and fancy game mechanics, but there isreally not much in the way of anything about a 2D platformer.Another goal was to show a simplistic and inexpensive approach to creating yourown game. Creating games is tough enough with the amount of time and effort youhave to put into it, and rising costs are something no indie developer wants to dealwith. Every element of this book uses free software and assets to build the game!Last, we wanted to write our book around a small game project. Using simpleapproaches to scripting and asset creation, we wanted to create a game that even someone new to Unity and game development could easily pick up and tackle. Every aspectof the project is covered in the book with clear explanations, examples, and images!Who Is This Book For?This book is for those who want to learn more about the process of creating a gameand all of the different parts that are involved, from having an initial idea, planning anddesigning, to the final steps of building and deploying the game to share with others.This book is also for those who are new to Unity and the new 2D tools that haverecently been integrated. We will touch on creating sprites and sprite atlases, applying2D physics, and adding game scripts, audio, and animations. Almost every aspect ofUnity is touched on and explained in detail.Why Did We Choose to Use Unity?The core of any game development is the game engine. It needs to handle all of therules, tasks, and mathematics thrown at it. It also needs to be able to grow and evolvewith new technology and the needs of the consumers playing the games.While it’s possible to develop your own game engine, starting with a well-structuredfoundation allows you to focus on creating your game content and letting the gameengine do the dirty work. There are a dozen great game engines that are capable ofthis, but Unity excels where others have failed.

xxPrefaceHaving started out as a great 3D game engine, Unity has blossomed into an end-alldevelopment tool for creating games that you can then push to just about every platform available. As time went on, the need for more 2D game tools became obvious,and Unity jumped onboard, creating some of the most intuitive and easy-to-use 2Dtools available.Another reason is how accessible Unity is. While the Pro version has some reallygreat additional features, they are tailored more to teams or people looking to reallyfine-tune every aspect of their game. We will cover a few of the Pro features, but thefree version will work great for us.What Will You Need?So what will you need to develop your game? After you have purchased this book, andassuming you have a computer to work on, there is nothing else to buy. All of the assetswe will use to create our game are accessible to anyone and readily available on theInternet, the obvious being the Unity engine, which is easily downloadable from theirWeb site (we cover this in the Introduction).For the game sprites we were lucky enough to get assets from a great game artist,Kenney Vleugels. We are including these with the ancillaries for this book, but checkout all of the amazing resources and game assets on his Web site, www.kenney.nl.He continually adds more and more assets and will even create specific assets at yourrequest.Last, all of the scripts for our game will be created within the chapters. We will beproviding the final scripts along with the project files, but we recommend you followalong and create them for yourself. Having a good grasp of even simple scripting willtake you a long way toward creating a game that is truly unique and completely yours.Register your book at informit.com/title/9780321957726 to access assets,code listings, and video tutorials on the companion website.How Much Scripting Is Involved?While we don’t dig down into the trenches of writing complex code behaviors, we docover a lot of the basics and create quite a few scripts throughout this book. Learning alittle programming can go a long way in any profession but is highly recommended forgame design. Even tests and debugging are helpful and require just a very basic level ofscripting knowledge.How Is the Book Organized?Our goal for this book was to have those reading it start from the beginning and worktheir way through it until the very end. Readers can build upon what they learned inprevious chapters and continually come back to elements they have already built. With

Prefacethese building blocks, we hope that at the end, you will have the confidence and skillto either continue building on the example project or start your own game design.However, we know this is not the case. There will be those who have an understanding of the game development process and are looking for a game authoring engineupon which to build their idea and designs. So we have broken each chapter down intoindividual lessons. That way those who are looking to learn about a specific mechanicor process can easily jump ahead.We encourage even those w

Learning 2D game development with Unity : a hands-on guide to game creation / Matthew Johnson, James A. Henley. Melissa Panagossegap mc Includes index. ISBN 978-0-321-95772-6 (pbk. : alk. paper)—ISBN 0-321-95772-5 (pbk. : alk. paper) 1. Computer games—Programming. 2. Unity (electronic resource) I. Henley, James A. II. Title. QA76.76.C672J64 .

Related Documents:

Game board printable Game pieces printable Game cards printable Dice Scissors Directions Game Set Up 1. Print and cut out the game board, game pieces, and game cards. 2. Fold the game pieces along the middle line to make them stand up. 3. Place game pieces on the START square. Game Rules 1. Each player take

Game Development Guide 092017 Game development resources 4 From documentation to developer programs, forums, blogs, and samples, there are many resources available to help you on your game development journey. Here's a roundup of resources to know about as you begin developing your Windows 10 game. Game development documentation

Board Game Design Theory and the Game Experience The idea of the game experience is at the heart of what makes our learning goals take on life, meaning and relevance to the game's participants. The game experience can be interpreted in many ways. In the following passages, the layers of the game .

[12] have developed a computer-based game called 'Golden Sugarcane', designed for young Thai students. The game is a competition-based game, allowing students to learn mathematics while they are playing on the game without feeling bored. An online game named 'Eternal Story' is also a well-known game based learning technique, which has

Design Your Own Game In this assignment, you will be designing your own game on your own in groups of 2. The game should be the type of game that you would play at a carnival, amusement park or casino. It cannot be a game that already exists— your group must create a unique game. Your game

During the Russian Game Developer's Conference, KRI-2004. . Your primary game input device is a computer mouse. You can control Dude, the main character, by clicking . - "Resume game": resumes current game, leaving the Game Menu. - "New game": starts a new game. W

game boy gallery 2 game boy wars game boy wars turbo game boy wars turbo - famitsu version game de hakken!! tamagotchi game de hakken!! tamagotchi - osutchi to mesutchi game de hakken!! tamagotchi 2 gamera - daikaijuu kuuchuu kessen ganbare goemon - kurofunetou no nazo ganbare goemon - sarawareta ebisumaru ganso!! yancha maru gb basketball gb .

The Battleship game was released as a plastic board game by the Milton Bradley Company (1967) The game has been popularized under the name "The Battleship game" by the Milton Bradley Company as it was published as a plastic board game in 1967. 4.1 The Original Battleship Game We provide description of the Battleship game as an interactive