Getting Started with Unity 5.x 2D Game Development - Francesco Sapio - E-Book

Getting Started with Unity 5.x 2D Game Development E-Book

Francesco Sapio

0,0
34,79 €

-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.
Mehr erfahren.
Beschreibung

Want to get started in the world of 2D game development with Unity? This book will take your hand and guide you through this amazing journey to let you know exactly what you need to build the games you want to build, without sacrificing quality. You will build a solid understanding of Unity 5.x, by focusing with the embedded tools to develop 2D games. In learning about these, along with accurate explanations and practical examples, you will design, develop, learn how to market and publish a delectable Tower Defense game about cupcakes versus pandas.
Each chapter in this book is structured to give you a full understanding on a specific aspect of the workflow pipeline. Each of these aspects are essential for developing games in Unity. In a step-by-step approach, you will learn about each of the following phases: Game Design, Asset Importing, Scripting, User Interfaces, Animations, Physics, Artificial Intelligence, Gameplay Programming, Polishing and Improving, Marketing, Publishing and much more.
This book provides you with exercises and homework at the end of each chapter so that you can level up your skills as a Unity game developer. In addition, each of these parts are centered on a common point of discussion with other learners just like you. Therefore, by sharing your ideas with other people you will not only develop your skills but you will also build a network.

Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:

EPUB
MOBI

Seitenzahl: 586

Bewertungen
0,0
0
0
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



Table of Contents

Getting Started with Unity 5.x 2D Game Development
Credits
About the Author
Acknowledgment
About the Reviewer
www.PacktPub.com
Why subscribe?
Customer Feedback
Preface
What this book covers
What you need for this book
Who this book is for
Conventions
Reader feedback
Customer support
Downloading the example code
Downloading the color images of this book
Errata
Piracy
Questions
1. A Flat World in Unity
Learning game development
Tower defense games
Designing our game
Getting ready
Remembering the past to build the future
Organizing the project
A 2D world
Sprites
Sprite Renderer
Importing new friends
The Sprite Editor
Manual mode
Automatic mode
Polygonal mode
Sprite Editor for UI-9-slice scaling
Preparing the assets
Scenes as levels
Setting proportions
There is more about the Unity interface
Homework
Summary
2. Baking Cupcake Towers
2D objects
Parenting game objects
Difference between world coordinates and local coordinates
Ordering the different layers with Z-Buffering
Unfolding the map
Layers and tags
Prefabs
The game view
Math background
Scripting in Unity
Creating new scripts
Basics about scripts
Variables
Attributes
Functions
Comments
Execution order
Making sprinkles
The projectile class
Scripting the projectile mother class
Tons of sprinkles through Prefabs
Baking cupcakes towers
What a cupcake tower does
Scripting the cupcake tower
Shooting to the pandas
Upgrading the cupcake tower, making it even tastier
A pre-baked cupcake tower through Prefabs
More about coding in Unity
Static variables
Inheritance
Random numbers in Unity
Homework
Summary
3. Communicating with the Player – the User Interface
Getting ready
Designing the user interface
Programming the user interface
User interface system
Canvas
Screen space – Overlay
Screen space – Camera
World space
Draw order of UI elements
Visual components
The Image component
The Text component
Basic transformations
The Rect Tool
The Rect Transform
Layout components
Fitters
Layout groups
The layout element component
Interaction components
The selectable base class
Interactable option
Transition options
Navigation options
Button
Toggle and Toggle Group
Slider
Scrollbar
Dropdown
Input Field
Scroll Rect
More about UI rendering
The canvas renderer
More visual components
UI effect components
UI and lights
The canvas components
Canvas group
Event system
Scripting user interfaces
Designing the interface for our game
Preparing the scene for the UI
Creating a health bar
Creating and placing the health bar
Scripting the health bar
Implementing the sugar meter
Creating and place
Scripting the sugar meter
More about UI scripting – handlers
What about all the rest?
Homework
Summary
4. No Longer Alone – Sweet-Toothed Pandas Strike
Getting ready
Animations
A historical overview
Animations in video games
Workflow for animations
Animations clips and the Animator component
Creating Animation clips with a controller
The Animator component
Creating the other animation clips
The Animator
The Animator window
The Animator state machine
The Animator states
Special states
The animator parameters
The animator transitions
Transition settings
Transition graph
Transition conditions
Testing transitions
The panda's Animation State Machine
Testing the panda's Animation State Machine
Scripting Animations
State machine behaviours
The destroy behaviour
The panda script
More about Animations
Avatars
Sub-state machines
The hierarchical location menu
Layers in the Animator
Blending trees
Animator Override Controller
Culling Mode in the Animator component
Root motion
Inverse Kinematic
Animator component information box
Legacy animation
Get animated!!
Homework
Summary
5. The Secret Ingredient Is a Dash of Physics
Getting ready
Physics in video games
Physics – basics
World coordinates and local coordinates
Velocity
Mass
Centre of mass
Kinematics
Dynamics
Force and torque
Collisions
Rigid body
Friction – linear and angular drag
The Unity Physics engine
Understanding Physics in Unity
Physics settings in Unity
Physics components
Rigidbodies
How a Rigidbody 2D works
Body types
Rigidbody properties
Dealing with rigidbodies
Colliders
Dealing with colliders
Joints
Main properties of Joints
The other rigidbody
Breaking joints
Specific joints
Distance Joint 2D
Fixed Joint 2D
Friction Joint 2D
Hinge Joint 2D
Relative Joint 2D
Slider Joint 2D
Spring Joint 2D
Target Joint 2D
Wheel Joint 2D
Effectors
Constant Force 2D
Area Effector 2D
Buoyancy Effector 2D
Point Effector 2D
Platform Effector 2D
Surface Effector 2D
Physics Material 2D
Dealing with physics in Unity
Other things about Physics
The Simulate setting on rigidbodies
Physics Raycaster 2D component
The other Physics settings
Gizmos for colliders
Physics for our game
Set up Pandas as a rigidbodies
Set up projectiles as rigidbodies
Detect sprinkles
Homework
Summary
6. Through a Sea of Sprinkles – Navigation in Artificial Intelligence
Getting ready
Introduction to artificial intelligence
The importance of artificial intelligence in video games
Navigation
Aspects of navigation
Pathfinding and its techniques
Waypoints for enemies
Getting the waypoint coordinates
Implementing waypoints – the first/static way
Implementing waypoints in the Game Manager
Moving along the designed path – static
Implementing waypoints – the second/dynamic way
Implementing waypoints as separate entities
Moving along the designed path – dynamic
More about artificial intelligence in games
Other techniques for navigation at the pathfinding level
Navigation at the level of steering behaviours
Navigation at the level of pathfinding/decision making – belief-driven pathfinding
Beyond navigation
Homework
Summary
7. Trading Cupcakes and the Ultimate Battle for the Cake – Gameplay Programming
Getting ready
What does gameplay programming mean?
Planning what is left to implement for our game
Trading cupcake towers
The trading parent class
Modifying the CupcakeTowerScript
Buying cupcake towers
Selling cupcake towers
Upgrading cupcakes towers
Adding the trading options to the user interface
Placing the towers
Sketching the idea of how it works
Allowed areas
Scripting the placement script
Selecting the towers
The Game Manager
Game over conditions
Game over feedback
The GameOver function
Keeping track of the game's progress
Panda invasion – spawning Pandas
What is a coroutine?
Sketching the idea of how it works
Setting up the spawning system
Managing waves
The single wave
The main menu
Designing the main menu
Creating the main menu in another scene
Loading scenes through scripts
Techniques we learnt in this chapter
Homework
Summary
8. What Is beyond the Cake?
Enhancing and improving your game
Improving cupcake towers
Shooting policies
Special sprinkles
Aging and pricing model
Improving the user interface
Improving levels
Multilevel
Large maps
Many paths
Many Pandas
Multiphase bosses
A better spawning system
Switching difficulty at runtime
Training and extending your Unity skills to become a better game developer
Making things easier for other team members
Exposing events
Sprinkles pooling
Saving your data
Debugging
Remote Logs
Cleaning the release version
More about communication between scripts
Documenting the code
Protecting your game
Building for more than one platform
Input/output devices
Virtual reality in Unity
Balancing the game
Extending the Unity editor
Multiplayer and networking
Practice makes perfect
Improving the atmosphere of the game
Visuals
Color schemes
Homework
Lighting
Lights in Unity
Homework
Environment
Homework
Special effects
Particle systems
Post processing
Other visual effects
Audio
Music
Sound effects
Eliciting emotions
Homework
Audio in Unity
External audio systems
Teamwork
It is not just about you, it is about working in a team
Sharing a common vision
Managing expectations
Collaboration and communication are key
Ways to communicate
Version control
Make a GDD and stick to it
Keeping it tidy with project management tools
Slack
HacknPlan
Drive
Dropbox
Trello
Redbooth
GitHub
BitBucket
Calendar
Pinterest
Hootsuite
Polishing your game
Processing the power
Checking the build size
Texture optimitation
Stats and profiling
Other optimization tips
Playtesting
Why are you even playtesting?
Exercise
Whom do you need to playtest?
The solo test run
Making it a social occasion
Putting it within boundaries
Reaching out to family and friends
Those who are strangers
Those who you want to play your game
When
Where
What
A little goes a long way
How
Methods of playtesting
Observe
Question and explain
Reflect and follow up
Creating your online presence
Do your research
Conducting an audit
Engaging with your audience
Rewarding engagement
Marketing on social media
Blog about it
Twitter
Exercise
Instagram
Facebook
MailChimp
Getting ready to publish
Crowdfunding campaigns
Building in Unity
Clearing the air
Accepting terms and conditions
Localization
Ethical considerations
Summary
Final notes and goodbye

Getting Started with Unity 5.x 2D Game Development

Getting Started with Unity 5.x 2D Game Development

Copyright © 2017 Packt Publishing

All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.

Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book.

Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.

First published: February 2017

Production reference: 1080217

Published by Packt Publishing Ltd.

Livery Place

35 Livery Street

Birmingham 

B3 2PB, UK.

ISBN 978-1-78439-717-3

www.packtpub.com

Credits

Author

Francesco Sapio

Copy Editors

Vikrant Phadkay

Safis Editing

Reviewer

Lauren S. Ferro

Project Coordinator

Nidhi Joshi

Commissioning Editor

Ashwin Nair

Proofreader

Safis Editing

Acquisition Editor

Larissa Pinto

Indexer

Mariammal Chettiyar

Content Development Editor

Mayur Pawanikar

Production Coordinator

Aparna Bhagat

Technical Editor

Dinesh Pawar

About the Author

Francesco Sapio obtained his computer science and controls engineering degree from Sapienza University of Rome, Italy, with a couple of semesters in advance, graduating summa cum laude; he is currently studying there for a master's of science and engineering degree in artificial intelligence and robotics.

He is a Unity 3D and Unreal expert, skilled game designer, and experienced user of major graphics programs. He developed Game@School (Sapienza University of Rome), an educational game for high-school students to learn concepts of physics, and the Sticker Book series (Dataware Games), a cross-platform series of games for kids. In addition, he worked as consultant for the (successfully funded by Kickstarter) game Prosperity – Italy 1434 (Entertainment Game Apps, Inc) and for the open online collaborative ideation system titled Innovoice (Sapienza University of Rome). Moreover, he has been involved in different research projects such as Belief-Driven Pathfinding (Sapienza University of Rome), which is a new technique of path finding in video games that was presented as a paper at the DiGRA-FDG Conference 2016; and perfekt.ID (Royal Melbourne Institute of Technology), which included developing a recommendation system for games.

Francesco is an active writer on the topic of game development. Recently, he authored the book Unity UI Cookbook, Packt Publishing. It teaches readers how to develop exciting and practical user interfaces for games within Unity, and he wrote a short e-guide, What do you need to know about Unity, Packt Publishing. In addition, he co-authored the book Unity 5.x 2D Game Development Blueprints, Packt Publishing, which has also been transformed in the video course Unity 5.x Game Development Projects, Pack Publishing. He has also been a reviewer for the following books: Game Physics Cookbook, Packt Publishing, Unity 5.x by Example, Packt Publishing, and Unity Game Development Scripting, Packt Publishing.

Francesco is also a musician and a composer, especially of soundtracks for short films and video games. For several years, he worked as an actor and dancer, where he was a guest of honor at the Teatro Brancaccio in Rome. In addition, he has volunteered as a children's entertainer at the Associazione Culturale Torraccia in Rome. Finally, Francesco loves math, philosophy, logic, and puzzle solving, but most of all, creating video games—thanks to his passion for game designing and programming.

You can contact him at www.francescosapio.com.

Acknowledgment

I'm deeply thankful to my parents for their infinite patience, enthusiasm, and support throughout my life. Moreover, I'm thankful to the rest of my family, in particular to my grandparents, since they have always encouraged me to do better in my life with the Latin expressions Ad maiora and Per aspera ad astra.

I also want to thank Lauren S. Ferro, the reviewer, for her fantastic feedback and help, which have enhanced the quality of this book. Another important person, without whom this book couldn't have seen the light, is Mayur Pawanikar, the content development editor, who supported me throughout the whole process.

Finally, a huge thank to all the special people around me whom I love. In particular to my girlfriend: I'm grateful for all of your help in everything, I love you.

About the Reviewer

Lauren S. Ferro is a gamification consultant and designer of game and game-like applications. She has worked, designed, consulted, and implemented strategies for a range of different purposes from professional development, recommendation systems, and educational games. She is an active researcher in the area of gamification, player profiling, and user-centered game design. Lauren runs workshops both for the general public and companies that focus on designing user-centered games and game-like applications. She has written a book about implementing gamification within Unity titled Gamification with Unity 5.x and is the developer of the game design resource Gamicards, which is a paper prototyping tool for both game and game-like experiences.

www.PacktPub.com

For support files and downloads related to your book, please visit www.PacktPub.com.

Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at [email protected] for more details.

At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters and receive exclusive discounts and offers on Packt books and eBooks.

https://www.packtpub.com/mapt

Get the most in-demand software skills with Mapt. Mapt gives you full access to all Packt books and video courses, as well as industry-leading tools to help you plan your personal development and advance your career.

Why subscribe?

Fully searchable across every book published by PacktCopy and paste, print, and bookmark contentOn demand and accessible via a web browser

Customer Feedback

Thank you for purchasing this Packt book. We take our commitment to improving our content and products to meet your needs seriously—that's why your feedback is so valuable. Whatever your feelings about your purchase, please consider leaving a review on this book's Amazon page. Not only will this help us, more importantly it will also help others in the community to make an informed decision about the resources that they invest in to learn.

You can also review for us on a regular basis by joining our reviewers' club. If you're interested in joining, or would like to learn more about the benefits we offer, please contact us: [email protected].

Preface

When Packt asked me to write this book, we had in mind something more modest than the book that you have today. While I was writing, I realized how many books can be found on the shelves that teach the basics without giving any practical insight on how to use that knowledge to actually make a game. Therefore, I slightly deviated the course of this book. As a result, it has changed into a somewhat solid manual about Unity, with a particular focus on 2D game development. The book that you are holding in your hands (either hard copy or on your tablet) is the outcome of a lot of effort trying to create something that is easy for the readers to understand, without sacrificing completeness or practical use of the different tools learned. Thus, everything is explained in detail, along with many examples of usage.

Also, I felt that another big deficiency of many books is the lack of Homework sections that provide the reader with exercises to improve her/his skills. In fact, I believe that these sections are important, since they provide a common ground in case you want to challenge yourself and take the discussion beyond the book with your friends, course mates, or colleagues. In the field of game development, it's important to collaborate, because a game is often the result of the coordinate efforts of many talented and passionate people.

For this book, I decided to support the learning of the different tools we will face by building a tower defense game on the joyful and sugary theme of cupcakes, sprinkles, and sweet-toothed pandas who will try to bite the delicious player's cake. This project will guide the reader through the book, and help her/him to develop a practical skillset as well.

Whoever you are, a hungry student of knowledge, a professor looking for a book to adopt in your classes, an expert in game development trying out Unity (or willing to extend your understanding of Unity), or just a passionate hobbyist, I hope you will enjoy this book.

What this book covers

Chapter 1, A Flat World in Unity, is an introduction to the 2D world of Unity. You will discover how to set up your project, import assets, and make them ready to use. In particular, we will go through in detail on how to use the Sprite Editor.

Chapter 2, Baking Cupcake Towers, teaches you how to integrate code within your game. We will cover the important and fundamental concepts of Unity and we will see how to script game objects by starting to create the behaviors of our cupcake towers for the tower defense game we are building.

Chapter 3, Communicating with the Player – the User Interface, deals with the important task to provide feedback to your players through the use of user interfaces (UIs). You will learn how to design them by discovering the general principles behind them, and learn how to implement any UI within the UI system of Unity.

Chapter 4, No Longer Alone – Sweet-Toothed Pandas Strike, introduces us to the terrible sweet-toothed Pandas, who will try to steal the player's cake. You will learn how to bring characters to life by using the powerful animation system of Unity Mechanim, starting from Sprite-sheets.

Chapter 5, The Secret Ingredient Is a Dash of Physics, takes you by hand deep down into the secrets of physics and explains them in a clear and easy way. You will grasp the basics of physics, and learn how to use the 2D Physics engine of Unity.

Chapter 6, Through a Sea of Sprinkles – Navigation in Artificial Intelligence, is an introduction to the universe of artificial intelligence applied to video games. You will learn the basics principles and how to implement a navigation system in Unity for 2D (or even 3D) games, so that we can make our terrible sweet-toothed Pandas move!

Chapter 7, Trading Cupcakes and the Ultimate Battle for the Cake – Gameplay Programming, wraps everything we saw and learned in the previous chapters to conclude the tower defense game. In particular, we will deal with gameplay programming, which is the glue between the different parts of your game.

Chapter 8, What Is beyond the Cake?, explores different aspects of our game and game development in general. You will discover different tips, tricks, and suggestions on how to improve the game we built in this book, along with improving your own skills to become a better game developer. Then, the chapter will give you an understanding of parts of the game development pipeline, which are not strictly tied to the development of the game itself. Thus, you will dive into different topics ranging from playtesting, optimizations, team management and work, documentation, getting ready to publish your game, marketing, social media, game protections, to even localization.

What you need for this book

To go through the topics covered in this book, you will need two important things:

Any version of Unity, possibly 5.x since it was the range of versions that this book has been written for. As you already know, and Chapter 1, A Flat World in Unity, will repeat, you can get it from the Unity official website: http://www.unity3d.com.Your enthusiasm and passion, in order to take an awesome journey in the world of game development together!

Who this book is for

Anyone including students, game enthusiasts, and academic professors who want to adopt this book as part of their course and classes. 

Conventions

In this book, you will find a number of text styles that distinguish between different kinds of information. Here are some examples of these styles and an explanation of their meaning.

Code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles are shown as follows: "All of them are placed inside a folder named Assets, which can be found inside the Project folder."

A block of code is set as follows:

public AwesomeUnityDeveloper GettingStarted(Yourself you) { you.ReadThisBook(); return you; }

When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:

public AwesomeUnityDeveloper GettingStarted(Yourself you) { you.ReadThisBook(); return you; }

New terms and important words are shown in bold. Words that you see on the screen, for example, in menus or dialog boxes, appear in the text like this: "First of all, if you ever need to switch between 2D and 3D mode, you can do so by navigating to Edit | Project Settings | Editor."

Note

Warnings or important notes appear in a box like this.

Tip

Tips and tricks appear like this.

Reader feedback

Feedback from our readers is always welcome. Let us know what you think about this book-what you liked or disliked. Reader feedback is important for us as it helps us develop titles that you will really get the most out of. To send us general feedback, simply e-mail [email protected], and mention the book's title in the subject of your message. If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide at www.packtpub.com/authors.

Customer support

Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.

Downloading the example code

You can download the example code files for this book from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.

You can download the code files by following these steps:

Log in or register to our website using your e-mail address and password.Hover the mouse pointer on the SUPPORT tab at the top.Click on Code Downloads & Errata.Enter the name of the book in the Search box.Select the book for which you're looking to download the code files.Choose from the drop-down menu where you purchased this book from.Click on Code Download.

Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:

WinRAR / 7-Zip for WindowsZipeg / iZip / UnRarX for Mac7-Zip / PeaZip for Linux

The code bundle for the book is also hosted on GitHub at https://github.com/PacktPublishing/Getting-Started-with-Unity-5.x-2D-Game-Development. We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!

Downloading the color images of this book

We also provide you with a PDF file that has color images of the screenshots/diagrams used in this book. The color images will help you better understand the changes in the output. You can download this file from https://www.packtpub.com/sites/default/files/downloads/GettingStartedwithUnity5x2DGameDevelopment_ColorImages.pdf.

Errata

Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books-maybe a mistake in the text or the code-we would be grateful if you could report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded to our website or added to any list of existing errata under the Errata section of that title.

To view the previously submitted errata, go to https://www.packtpub.com/books/content/support and enter the name of the book in the search field. The required information will appear under the Errata section.

Piracy

Piracy of copyrighted material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works in any form on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy.

Please contact us at [email protected] with a link to the suspected pirated material.

We appreciate your help in protecting our authors and our ability to bring you valuable content.

Questions

If you have a problem with any aspect of this book, you can contact us at [email protected], and we will do our best to address the problem.

Chapter 1. A Flat World in Unity

This is the beginning of our journey in to the world of 2D game development with Unity. This book is structured to guide you through the creation of an entire 2D game from scratch, in particular a tower defense game.

Despite the fact that we will focus on 2D game development, our final goal is to learn how to use Unity, and therefore this means that we will also have a glance at how Unity handles 3D. So, if later on you want to dedicate some time to 3D games, by the end of this book you will have the necessary background for doing so. In fact, the book is structured to contain as much detail as possible for each topic, and this includes historical overviews and references to further readings.

In every chapter, we will face different challenges that will improve our skills. Furthermore, this book doesn't stop by telling you just what needs to be done (like many others), but it also explains the different tools that we will encounter and how to use them. In this way, we will learn how to use and apply them in different contexts as well. Thus, you can use this book as a reference manual, in order to speed up your workflow. To help you out, I recommend that you use the index, to quickly locate each one of the specific topics we will face.

At the end of each chapter, there is a Homework section, which leaves you with some exercises that are related to the topics that we have dealt in that chapter. Of course, you are free to skip this section, but I recommend that you do the exercises if you feel that you need to improve your skills even more.

For now, this chapter is an introduction to the 2D world inside Unity, and what needs to be done in order to create our game. In particular, we will look at the following topics:

What are 2D games?What does designing and developing 2D games mean?Where to get Unity and its different versionsDownloading a graphical package from an external sourceHow to organize a project in UnityUnderstanding Unity when it is set in 2DWhat are Sprites?The Sprite Renderer componentImport settings for SpritesHow to use the Sprite Editor with all its different modesPreparing the assets for our gameSetting up scenes and proportions

One last thing. Sometimes I'll refer to the player and to characters in order to make examples or explain concepts. As such, sometimes I'll refer to them as if they were males, and at other times as if they were females (and sometimes both). The reason derives from my personal point of view so as to not to discriminate between the two genders.

And with this said, let's get started!

Learning game development

Game development and design are some of the most extensive works of art around. This is due to the large amount of expertise that is required to bring a game to life. You can get an idea of this by just looking at any credits in a game. They are extensive and contain a lot of names of people who have dedicated a lot of their time to the game in various roles.

Like most things in life, game development can be learned not only through practice, but iteration as well. And even when you master one of the many branches in game development, there is still something new to learn.

Regardless of your level of knowledge of Unity, I strongly suggest that you follow each step in this book, even if you think you know the topic. You just never know, there is always something new to learn!

Tower defense games

Tower defense games come in many different styles. For example, in the following screenshot of Defense Grid: The Awakening and Unstoppable Gorg, both are top-down isometric style games. However, they are set in different worlds, with different objectives. So, given this, what makes a tower defense game? For one, they are centered on the idea of defending something, whether it is buildings, resources, weapons, and so forth. This is the main mechanism that defines the genre and drives the gameplay. Secondly, most tower defense games require economic and resource management. For example, after each wave of enemies, you may obtain a certain amount of virtual currency that you must then allocate to either the purchase of new defenses (weapons, towers, and so on) or upgrades. Each has their benefits depending on a range of factors such as weak points in your defense as well as the anticipated amount and strength of enemies that will be in the next wave. The number and difficulty of enemies increases after each wave, therefore challenging the player to manage resources and build defenses strategically. The idea is to build up enough resources to upgrade your defenses and to outlast the incoming wave. Sometimes, the player must stop the enemies (or an opponent) from destroying their own base.

In other cases, the player must prevent the enemies from reaching the end, as each enemy that manages to get through cause damage to the player's health bar.

(Top) Defense Grid: The Awakening and (bottom) Unstoppable Gorg

There are many places on the Internet where you can find tower defense games. For example, Kongregate (http://www.kongregate.com/) and Newgrounds (http://www.newgrounds.com/) are examples of sites where a varied array of free tower defense games exist (such as Kingdom Rush or Bloons Tower Defense 5). However, many exist for iOS (App Store) and Android (Play Store), operating systems such as Linux, OSX, and PC (for example, Steam), and consoles (Playstation, Xbox), and so on.

Designing our game

Before you even think about turning your computer on, you need to design your game. It's not enough to have a rough idea in mind. You need to write down all your ideas before hand to start working. The first phase of game design is brainstorming. There are different techniques and methodologies of brainstorming that, unfortunately, we don't have the time, in this small section, to describe. However, the final outcome should be tons of paper with thousands of ideas written down. It's not meant to be a work of art, but the foundations upon which your game will be built.

Note

Some information about brainstorming can be found also in a practical book, Gamification with Unity, by Packt publishing. You can find it here: https://www.packtpub.com/game-development/gamification-unity-5x.

The next step is to refine your ideas, discard (or keep for other projects) the ones that you don't need, and organize them in a coherent form.

The final result should be something like the following.

Panda Invasion is a 2D tower defense game. In fact, hungry pandas are invading to steal all the sugar from the player. He or she has to push back the pandas by using cupcake towers. There are different kinds of cupcake towers that the player can decide to place in the map. In every level, there will be a path that pandas will follow. Furthermore, they are spawned at the beginning of this path. At the end, there is the ambitious sugar castle that the player has to defend. If the pandas steal too much, bringing the sugar-meter to zero, the player has failed his or her important mission. On the contrary, if he or she is able to push all of them back, the player will gain victory. However, cupcake towers are not free. In fact, the player has to buy them by using candy. Every time that a panda is pushed back, then the player will earn a certain amount of candy. Furthermore, the player can use candy to upgrade the cupcake towers and make them even stronger!

From this excerpt, you are now able to understand what we are going to do in this book. You also have a basic idea of how to write down your ideas. I strongly suggest that you always do this step, even when you are the only developer, and especially when you have a team.

Getting ready

Now that we have our idea, the next thing to do is to get Unity. It comes in different versions: Personal (which is free), Plus, Professional, and Enterprise. The last three contain more features than the Personal one. However, all the topics covered in this book can be done with the free version. In any case, you can get or buy Unity on the official website: www.unity3d.com.

This is the comparison screen between the different versions of Unity on the Unity Technologies website (if you scroll down, you will find which feature is included in which version):

Note

This is a very short summary of how model pricing for Unity has varied in recent years. In fact, to become a developer also means to be aware of the world around you, and having basic marketing knowledge could also help. At the beginning, the model price of Unity didn't allow developers to publish commercial games with the free version. In addition, the game engine didn't have all the features, such as the Profiler or the Movie Textures. Epic Games, the company that owns Unreal Engine, changed its model prices by making its game engine free in March 2015, also for commercial use (although it will take in return the 5% of the game's gross revenue). After a period of time, Unity Technologies also allowed developers to publish commercial games even with the free version, but it was still watermarked. From Unity 5.x, features that were only in the Pro version became available in the free version as well. During the beginning of 2016, Unity used to come in two different versions: Free (or Personal) and Professional. The latter contains more features than the Personal one, and here is the comparison screen of the two:

In June 2016, Unity changed its price model in the one described earlier.

Once we have installed Unity, we can begin creating new projects. If we click on the New project button in the top-right corner of the window, Unity will ask us to insert the details for our project. We can name it Panda Invasion and choose the destination path, which is where the files of the project will be stored. There is another an important thing to note. Unity gives us the possibility to choose between a 3D and a 2D project. This is not important decision, since it can be changed at any time. However, it is useful to already have in mind whether or not the game will be 2D or 3D. By selecting the 2D mode, Unity adapts the default settings to the game that we have in mind. We will see these settings in the following sections. For now, you should have a screen that looks like the following:

Now, we can press the Create project button, and we have successfully created our project and are ready to build it.

This book assumes that you are fairly familiar with the Unity interface and with C# code. If you are not, don't worry. There are different ways that you can learn before continuing on with this book. For example, I wrote a small free e-guide that briefly goes through the main interfaces and concepts of Unity. Don't expect to learn all you need from there, but it is a good start. You can find it at https://www.packtpub.com/packt/free-ebook/what-you-need-know-about-unity-5. If you are a complete newcomer to Unity, please read that small e-guide. I'll still be here once you have finished and we can resume our awesome journey. Furthermore, the official manual of Unity and its documentation are great companions in the Unity game development world. You can find them both on the official website, at https://docs.unity3d.com/Manual/index.html.

Since we don't have the time to create our own graphics for the game that we are going to develop, we need to download a custom package. Of course, you are free to choose the one you like most. For this book, we are going to use the Tower Defence Pack 2 package, which can be downloaded from http://player26.com/.

Note

Tower Defence Pack 2 features a delicious assortment of cupcakes ranging from infamous fluffy white frosting and colorful sprinkles, to decadent chocolate chip, not to mention an all-time favorite, lemon meringue with silver dragees. It also features the Sugar Castle, a home away from home for candy lovers! In addition to all this sugary goodness are trees, mountains, rainbows, and various other assets to populate your sugary environment. Just be beware, there are some hidden dangers among it all with the pandas, so be careful to keep your stash well protected from thieving sweet-toothed animals!

The package includes all the basic assets that we need to create our tower defense game. It is free, even for commercial use, and even if credits are required. There is also a premium version that contains more assets and some of the decorations in different Sprites to increase customizability. In particular, in the free version we can find:

Maps designed for tower defense gamesEvil pandas (with animation)Three different upgrading levels for cupcakes towersMultiple icons for each object in the packageAnd many more assets to populate the level with!

The following image can give you an idea of the kind of graphics this package contains:

So, download this package before moving on to the next section.

Remembering the past to build the future

If you are new to Unity, or you have only used Unity 5.x, you can skip this section or read it just for curiosity.

In Unity 4.x (before version 4.6) and other previous versions, building 2D games was a bit harder. In fact, you needed to use a range of different methods and tricks to achieve the illusion on 2D. All the 2D objects were actually 3D objects viewed in a particular perspective or with a particular camera, which gave the illusion of a 2D object.

From Unity 4.6 on, and especially since Unity 5.x, this is not needed any more. There is built-in support for 2D games. So now, there are special components to deal with 2D objects, and the following sections will explore some of them.

Organizing the project

There are different ways to organize a project within Unity, therefore giving a bit more freedom. In this section, we propose one method, which we will use during the development of the project in this book.

The key idea is to organize the different assets by type (and not, as in other methods, by their position within the level).

First of all, let's understand how Unity organizes assets. All of them are placed inside a folder named Assets, which can be found also inside the Project folder. Therefore, all our assets should be contained in this folder or subfolder. In order to create a new folder, right-click on the Project panel and then Create | Folder. As a result, a new folder is created within the folder you clicked. Since we don't have any folders, it will be a subfolder of the Assets one. We have the option to rename it as we want. If you miss this, you can just select it and then click on it again (but not too fast, otherwise Unity will consider this as a double-click and it will open the folder), as shown in the following screenshot:

Note

It is important to note that Unity will ignore the following categories, in order to avoid importing system files:

Hidden folders and filesFolder and files that starts with ~ and with .Folders and files named cvsFiles which have a .tmp extension

We need to create the following folders (you should only create the ones in bold, since we will not use the other ones):

FontsGraphicsMaterialsAnimations (we will see them in more detail in Chapter 4, No Longer Alone - Sweet-Toothed Pandas Strike)Music and soundsOther assets (to store, for instance, .txt assets)Physical materialsPrefabs (we will see what they are in the next chapter)ScenesScripts

Note

If you are planning to create a 3D game, the folders will be different and they will include other kind of assets, such as 3D models and textures.

At the end, we should see the following in our Project panel (I'll add the Animation folder in Chapter 4, No Longer Alone - Sweet-Toothed Pandas Strike, when we will see animations, but feel free to add it immediately if you like):

There is something else to know about the folders in your projects. If you create folders with some specific names, Unity will treat them in a special way. We are not going to use them; however, it's worth giving them a quick look:

Editor (or a subfolder within it): This contains editor scripts rather than runtime scripts. These are designed to implement new functionality in Unity during the development of your games, and will not be included in the published game. As a result, you cannot use any of the scripts inside this folder within your Scene. Furthermore, it's possible to use more than one Editor folder in your project (even if this affects the execution order).Editor Default Resources: This contains resources that can be loaded on-demand by editor scripts by using the EditorGUIUtility.Load() function.Resources (or a subfolder within it): This contains all the assets that can be loaded on demand from a script by using the Resources.Load() function. In fact, you may need to load an asset that is not present in the scene yet. As with the Editor folder, you can have as many as you want in your project.Plugins: This contains native DLLs, written in C/C++, which can access third-party libraries, system calls, and other functions that Unity doesn't provide directly. As the name suggests, it is used to implement or import plugins.StreamingAssets: This contains assets that will not be included in your main game file, but that can be streamed from a script.WebPlayerTemplates: This contains custom host pages to use when the target platform is the WebPlayer. Scripts in this folder will not be compiled.

Coming back to our folder, we need to import the package that we have downloaded. This can be done in a number of different ways, but the easiest way is to drag and drop the folder of the package within our Graphics folder.

If you need to select an asset to use, in the bottom-left corner of the Project panel, there is a slider that allows you to increase the size of the icons in the Project panel. This function is useful when there are a lot of assets and we need to find the right one without knowing the name, or when exploring new packages we don't know yet. The slider is highlighted in the following screenshot for your convenience:

A 2D world

There are few things to notice in our project when it is set to 2D mode, which we are going to explore in this section.

First of all, if you ever need to switch between 2D and 3D mode, you can do so by navigating to Edit | Project Settings | Editor. If you go in to the Default Behavior Mode settings, you can change the Mode, as shown in the following screenshot:

Coming back to our main interface, let's see the main differences between 2D and 3D mode. The Scene view is set by default to 2D, as you can see in the following screenshot:

This allows us to have the Scene view locked on to the xy plane.

Note

The z axis is used to determine which object should be rendered first. This decides which objects are in the foreground and which ones are in the background.

Then, every time we create a new scene, the default camera that comes with it is always set in Orthographic mode. Furthermore, its position is set to (0, 0, -10), whereas in 3D mode, it is set to (0, 1, -10). You can also check this by selecting the Main Camera in the Hierarchy panel and seeing its properties in the Inspector, as shown in the following screenshot:

Other differences are the options to use the Sprite Packer or the default objects that don't have real-time directional lights. There are also changes in the Lighting settings (you can access them from Window/Lighting). In particular, the Skybox is disabled for new scenes and Precomputed Realtime GI, Baked GI, and Auto-Building are set to off. In addition, the Ambient Source comes with a dark grey color.

In the following screenshot, you can see the default Lighting settings:

Note

The RGB code of the color of the Ambient Source that is set by default in the 2D mode is (54, 58, 66).

However, the most important difference is how Unity imports new 2D assets, but we are going to see this in detail in the following sections.

Sprites

The fundamental bricks of a 2D game in Unity are the Sprites. You can think of them as pictures, but actually as we are going to see, they are something more. In fact, one image can contain more than one Sprite. Usually, this kind of image takes the name of a Sprite Sheet. Here is an example of a Sprite Sheet within our package:

There are different reasons why we want to have all the Sprites on a single image, rather than display them separately. The most important one is efficiency. Every time you want to render something on the screen, this has to be rendered by the graphics card in your computer. If all the Sprites are in separate images, the graphics card will have to process a lot of images. As a result, your game will run slowly.

Another reason for having Sprite Sheets is for animations. While 3D animations are made of data that describes how a 3D model has to be moved, 2D animations are made of frames. Like a movie or a cartoon, an animation is made of different images, or in this case, Sprites. Each of them describes a moment, and if you change them quickly enough, such as 25 per second, you can give the illusion of movement. Having all of the frames in a unique image is both efficient and well organized.

Naturally, there are other reasons for Sprite Sheets, but the two preceding reasons should be enough to convince you that Sprite Sheets are the best practice. On the other hand, there is a tradeoff to pay: the game engine needs to be able to distinguish between them on the image. We will see how Unity handles this in the following sections. But before we move on, there are other important concepts to learn about Sprites in Unity.

Like a 3D object, a Sprite also has a pivot point. Usually, this is located in the middle, but it can be changed in the Sprite Editor. The pivot point is where Unity starts to do all the calculations from. For instance, when you give a position for the Sprite to be within the Scene, Unity places the pivot point in that specific location, and then draws the Sprite around it. The pivot point is also important for rotations. Every time we rotate the Sprite, the rotation will be around the pivot point. In other words, during a rotation, the pivot point is the only point that does not change position.

This can be better explained with a screenshot, where the arrow is indicating the location of the pivot point:

As you can see, there is the same Sprite rotated by 90 degrees clockwise. The one on the left has the pivot point in the middle, whereas the one on the right has it toward the left-hand side (the pivot point can be identified by the blue circle). Of course, you can make them coincide with a translation, but it is important to keep where it is in mind, especially when we code, in order to easily achieve what we want.

Now, there is another aspect to take into account about Sprites. In a 2D game, both the background and the character who is moving around the world are considered Sprites. However, we would like to render the background behind the character, and not vice versa. Therefore, the Sprites are rendered in a certain order that determines which one should render on top of the others.

In Unity there are two main ways to decide this order:

Sorting Layers: Each Sprite Render, which is a component attached to a game object that renders the Sprite selected, has a variable called Sorting Layer. There, we can chose on which layer the Sprite will be rendered. The order of the different sorting layers can be determined in the Tags and Layers Settings (we will see how to access this menu later on in the chapter). Furthermore, Sorting Layers can offer an internal order for Sprites within the same layer by using the Order In Layer variable, which is always in the Sprite Render component.Z-Buffering: Since a 2D object only needs two coordinates to describe its position (the x and y axes), we have the z axis to describe depth. Unity uses depth to determine which Sprite should be rendered first. Since you need to imagine this as a depth, it's good practice to use only negative values. The greater the negative value, the closer the character or object is to the camera.

There aren't any great differences between these methods in terms of computational efficiency. Therefore, both can be used. Actually, they can also be used together. A general approach is to use the z axis for visually structuring characters. Imagine a character who is carrying a weapon. Depending on which hand the weapon is held in and in which direction the character is facing, the weapon should be rendered behind the character or in front of it. Sorting Layers, instead, are used for organizing the Sprites at a higher level, such as background, foreground, player, enemies, and so on.

However, for the sake of learning, in this book we will not use Sorting Layers, but only Z-Buffering, since it can be easily changed within the code.

Sprite Renderer

Before we mention this component, it might be worth discussing it a bit more.

This component will be automatically attached every time we add a Sprite to the scene. It should look like the following screenshot:

Let's break down the different parameters:

Sprite: This holds the Sprite that it has to render.Color: This is a color that is multiplied to the Sprite image. If you know bit about shaders and renderers, this is actual the vertex color of the rendered mesh.Flip: This defines on which axis the Sprite needs to be flipped. This is a new function from Unity 5.3.Material: This is the material Unity should use to render the Sprite. The default one is more than enough for our needs. If you are an expert in shaders, there are two kinds of built-in shader. Both are simple alpha-blended shaders, but the Diffuse one interacts with light, generating a (0, 0, -1) front-facing normal vector.Sorting Layer: This is in which Sorting Layer the Sprite should be rendered (as discussed previously).Order in Layer: This is the order within that particular Sorting Layer (as we discussed previously).

Importing new friends

If you have downloaded and imported the package from the Getting ready section, we should now have all the files inside our Project folder. If you go to the Graphics/towers folder and select cupcake_tower_sheet-01, we should see the following in the Inspector:

These are the Import Settings, where different options can be set. After we have changed something, we need to press the Apply button at the bottom to confirm the changes. Likewise, if we are not happy, we can press the Revert button to discard our changes.

It is important to note that the Texture Type is Sprite (2D and UI). In 2D mode, Unity always imports image files as Sprites and not as Textures.

The other important parameter that we need to take into consideration is the Sprite Mode. By default, it is set to Single, but it can be changed to Multiple or Polygonal (only from Unity 5.3). As the names suggests, the first is used when the image contains a single Sprite, and the second mode is used when we have a Sprite Sheet with more than one Sprite. The last one is used to identify a polygonal Sprite with a custom number of edges.

Furthermore, the Pixel Per Unit parameter determines how big the Sprite will be in the Scene. It represents how many pixels are needed to have a unitary length in the Scene View. By default, it is set to 100, but you should modify this value when you need to adapt your assets and change them to the right dimensions. However, if you already have a scale in mind, creating the graphics accordingly could be a useful time saver for the later stages of development.

With regard to the other settings (Packing Tag, Generate Mip Maps, Filter Mode, Max Size, and Format), we will see them in detail in the last chapter of this book, when we will talk about optimization.

Since the file that we have selected contains more than one Sprite, let's set the Sprite Mode to Multiple before we move on to the next section.

The Sprite Editor

In Import Settings, there is also a button named Sprite Editor. If we press this button, a new window appears. This is the Sprite Editor, as we can see in the following screenshot:

If we mess things up, we can always revert them back by clicking on the Revert button in the top-right corner of the Sprite Editor. Next to it, you can also find an Apply button, which you use to confirm your choices, so be careful which one you press!

For your own reference, they are highlighted in the next screenshot:

Near these two buttons, you can find some features that might help you when working in the Sprite Editor. The first is a button that is easy to miss, but that allows you to switch from the colored asset (RGB channels) to B/W (alpha channel). This is particularly useful when you need to define contours and the image has transparency, as we will see later. So that you avoid missing it, you can find it highlighted in the following screenshot:

To the right of it, there are two sliders, which allow you to either zoom in/out or increase/decrease the resolution (number of pixels). These features are shown in the following screenshot:

The Sprite Editor allows you to do different things. For single sprites, it gives the possibility to change the pivot point. For Sprite Sheets, such as in this case, it is the way for Unity to understand how many Sprites there are and where they are located on the image.

Now, there are different ways to do this, so let's have a look at them in more detail.

Manual mode

In manual mode, it's you that selects each Sprite in the image, and tells Unity where it is and how big it is.

To create a new selection, you need to click in a corner of your Sprite and drag the mouse until you have selected the whole Sprite. A green rectangle appears, showing you the selected area, and you can see how the Sprite changes in real time while dragging the mouse. If you release the mouse button, the green rectangle becomes blue and Unity will interpret everything that is inside it as a Sprite.

You can create as many selections (rectangles) as you want. Also, by clicking on them, you can move them around the image and change their dimensions. Here is an example of our Sprite Sheet with some manual selections:

If you have made a rectangle that is bigger than the Sprite, Unity can try to trim it. In the top-left corner of the Sprite Editor, there is the Trim button, as shown in the following screenshot:

It is active only when a selection is highlighted. If you don't like the final result, you can always modify the selection.

Furthermore, in the middle of each selection, there is a small blue circle. This is the Pivot Point of that selection. We are free to drag it to another position. However, other than very specific cases, having the pivot point in the middle is common and useful. So at the moment, don't worry much about it, and just leave it in the middle.

Another thing you may notice is four small green squares in the middle of each edge of the rectangle. We will need them to do 9-slice scaling in a few sections.

Once we have highlighted a selection, it is possible to modify it in more detail by using the menu that appears in the bottom-right corner of the Sprite Editor. Here is what it looks like:

From this menu, you can modify the name of the selection, which will be reflected in the name of the Sprite when we use it. By typing numeric values, you can precisely set the dimension, the position, and the Pivot Point of the selection.

To conclude, manual mode is particularly useful when the shape and the dimensions of the Sprite in the Sprite Sheet are different. Even if the designer of the picture is careful and avoids placing single Sprites close to each other, the objects can still have very different dimensions.

Automatic mode

In automatic mode, Unity tries to slice the Sprites, which means it creates the different selections for you. However, to get a better result, you need to give some information about the image. In any case, once Unity has offered its selections for the image, you can still modify them as you would in manual mode.

In the top-left corner of the Sprite Editor, next to the Trim button, we can see the Slice button, as shown here:

By clicking on it, a menu appears that looks like this:

As you can see, we can select different types. Let's go through them.

The Automatic