Mastering Unity 2D Game Development - Ashley Godbold - E-Book

Mastering Unity 2D Game Development E-Book

Ashley Godbold

0,0
42,22 €

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

Master everything you need to build a 2D game using Unity 5 by developing a complete RPG game framework!

Key Features



  • Explore the new features of Unity 5 and recognize obsolete code and elements
  • Develop and build a complete 2D retro RPG with a conversation system, inventory, random map battles, full game menus, and sound
  • This book demonstrates how to use the new Unity UI system effectively through detailed C# scripts with full explanations

Book Description



The Unity engine has revolutionized the gaming industry, by making it easier than ever for indie game developers to create quality games on a budget. Hobbyists and students can use this powerful engine to build 2D and 3D games, to play, distribute, and even sell for free!

This book will help you master the 2D features available in Unity 5, by walking you through the development of a 2D RPG framework. With fully explained and detailed C# scripts, this book will show you how to create and program animations, a NPC conversation system, an inventory system, random RPG map battles, and full game menus. After your core game is complete, you'll learn how to add finishing touches like sound and music, monetization strategies, and splash screens. You'll then be guided through the process of publishing and sharing your game on multiple platforms. After completing this book, you will have the necessary knowledge to develop, build, and deploy 2D games of any genre!

What you will learn



  • Create a 2D game in Unity 5 by developing a complete retro 2D RPG framework
  • Effectively manipulate and utilize 2D sprites
  • Create 2D sprite animations and trigger them effectively with code
  • Write beginning to advanced-level C# code using MonoDevelop
  • Implement the new UI system effectively and beautifully
  • Use state machines to trigger events within your game

Who this book is for



This book is for anyone looking to get started developing 2D games with Unity 5. If you're already accomplished in Unity 2D and wish to expand or supplement your current Unity knowledge, or are working in 2D in Unity 4 and looking to upgrade Unity 5, this book is for you. A basic understanding of programming logic is needed to begin learning with this book, but intermediate and advanced programming topic are explained thoroughly so that coders of any level can follow along. Previous programming experience in C# is not required.

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

EPUB

Seitenzahl: 434

Veröffentlichungsjahr: 2016

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

Mastering Unity 2D Game Development - Second Edition
Credits
About the Authors
About the Reviewer
www.PacktPub.com
eBooks, discount offers, and more
Why subscribe?
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. Overview
Getting assets
Unity's 2D features
2D mode versus 3D mode
Working with sprites
Sprite Renderer
Sprite Editor
Sprite sheets
Texture atlases
Physics 2D
Changes to Unity 5
Licensing
Component access
Animator changes
Audio mixing
Summary
2. Building Your Project and Character
Project overview and structure
Project overview
Structure
Asset naming
Creating the project
Creating a scene
Sprite system
Importing sprites
Texture Type - Sprite (2D and UI)
Sprite Mode - Single/Multiple/Polygon
Packing Tag
Pixels Per Units
Pivot
Generate Mip Maps
Filter Mode
Default settings and per-platform overrides
Sprite Editor
Sprite slicer
Automatic
Grid By Cell Size and Grid By Cell Count (Manual)
View controls
Sprite region manipulation
Importing our main character
GameObjects and components
Sprite GameObjects
Bringing our hero into the scene
Classes
MonoDevelop
The object-orientated design
The game structure
The common game object
The player object
Planning behaviors
Behaviors for the common game object
Coding with components
Accessing components
Referencing a component
Controlling the hero
Going further
Summary
3. Getting Animated
Fundamentals of sprite animation
Animation clips
Animation Dope Sheet
The time/recording controls (1)
Animation drop-down selection (2)
The sample rate (frames per second) (3)
Animation properties (4)
Timeline (5)
Curve view (6)
The Animation Controllers
The Animator component
Animating the main character
Adding your first Animation Clip
Setting up the Animator and default state
Adding the other Animation Clips
Planning the animation transitions
Connecting the animation states
Accessing controllers from a script
Making her stop animating and face the correct direction
Going further
Summary
4. The Town View
Backgrounds and layers
To slice or not to slice
The town background
The town buildings and roads
The extra scenery
Building the scene
Adding the town background
Sprite sorting layers
Sprite Sorting Order
Updating the scene sorting layers
Building out the scene
Working with the camera
Comparing Update, FixedUpdate, and LateUpdate
Moving our camera with the player
The perils of resolution
Setting our aspect ratio and camera parameters
Transitioning and bounds
Towns with borders
Journeying onward
Going further
Summary
5. Working with Unitys UI System
UI Canvas
EventSystem
Canvas Render Mode
Screen Space - Overlay
Screen Space - Camera
World Space
Using multiple Canvases
UI Text and Images
UI Text
UI Image
UI Layout and Rect Transform
Rect Tool
Pivot
Anchors
UI Buttons
Transition types
Text child
On Click ()
Going further
Summary
6. NPCs and Interactions
Considering an RPG
Advanced programming techniques
Singletons and managers
The manager approach - using empty GameObjects
The singleton approach - using the C# singleton pattern
Communicating between GameObjects
Delegates
The configurable method pattern
The delegation pattern
Compound delegates
Events
Messaging
A better way
Background tasks and coroutines
Enter coroutines
IEnumerator
Yielding
Starting coroutines
Closing the gap
Serialization and scripting
Saving and managing asset data
Using the serialized files in the editor
Accessing the .asset files in the code
Adding NPCs and a conversation system to our game
Let the player walk around the NPC
Stopping the player from walking through the NPC
Getting the NPCs talking
The conversation object
Saving and serializing the object for later
The conversation component
Building a basic conversation system
The manager
Starting a conversation
Preparing the UI
Displaying the conversation
Connecting the dots
Going further
Summary
7. The World Map
The larger view
Types of map
Fixed maps
Generated maps
In-game generated maps
Going procedural
Creating our game's map
Adding the world map
Adding a player prefab to the overworld
Adding places of interest
Leaving town
Creating a NavigationManager script
Blocking off paths
Updating build settings to include new scenes
Changing scenes
Returning to town
Updating the NavigationManager script
Going further
Summary
8. Encountering Enemies and Running Away
Event systems
Exploring randomness
True randomness
Planning for random code/generation
Basic Artificial Intelligence
State machines
Defining states
Simple singular choice
Planning for multiple cases
State managers
Sensors
Setting up your battle scene
Building the new scene
Adding the first enemy
Spawning the Dragons
Creating the BattleManager
Allowing the player to run away
Starting the battle
Saving the map position
Stop immediately re-entering battle
Going back to town
Going further
Summary
9. Getting Ready to Fight
Setting up our battle state manager
The battle state manager
Getting to the state manager in the code
Starting the battle
Introductory animation
Efficient RPG UI overlays
The adventurer's overlay
A context-sensitive overlay
Modern floating UI approach
Balancing the need
Bring on the GUI
Laying out the HUD
Displaying the correct buttons
Going further
Summary
10. The Battle Begins
Designing an interesting battle system
Leveling up
Balancing
Preparing to attack a single enemy
Beefing up the enemy AI
The enemy profile/controller
Updating the Dragon prefab
Setting up the enemy profile in the code
Selecting an attack
Adding a visual effect to attack selection
Selecting a target
The selection circle prefab
Adding selection logic to the EnemyController class
Attack! Attack!
Using particle effects to represent an attack
Creating the materials for the particle effects
Adding the particles
Displaying the particles upon attack
Finishing up the battle
Going further
Summary
11. Shopping for Items
Why do we shop?
The power of an item
Building your shop
Laying out your inventory
Rule of 99'
Encumbrance systems
Slot-based systems
A mini game
Real world
Creating a shop and inventory
Gathering shop assets
Building the shop scene
Creating inventory items
Managing the shop
Updating the player inventory definition
Stocking the shop
Linking up the buttons
Turning off the Buy Button
Entering the shop
Leaving the shop
Managing your inventory
Adding objects to the player's inventory
Going further
Summary
12. Sound and Music
Choosing the appropriate sound and music
Where to get sound and music for your game
Free resources
Audio listeners and audio sources
Adding background music
Creating a splash screen
Adding the audio source
Transitioning to the next scene
Keeping the music after the scene transition
Adding sound effects
Adding a sound to the buy button
Muting/unmuting audio
Going further
Summary
13. Putting a Bow on It
Building in-game menu structures
The screens
Splash screens
Loading screens
The main menu
Save slots/level selections
Settings pages
The About screen
Privacy policy
Pause screens
Additional menus (purchasing, achievements, leaderboards, and so on)
Social
The flow
Finishing our splash screen
Building our start screen
Extending the editor
The property drawers
Examples property drawers
Built-in property drawers
Custom property drawers
Custom editors
The editor window
Gizmos
Building your editor menus
Adding a MenuItem attribute
Enabling/disabling a MenuItem attribute
Adding shortcut keys to a MenuItem attribute
Adding contextual MenuItems
Running scripts in the Editor folder
Alternative approaches
The [InitialiseOnLoad] attribute
Editor application callbacks
Mixing it up
Working with settings
Using PlayerPrefs
Serializing your data
Saving data to disk
Backing up to the Web
Going further
Summary
14. Deployment and Beyond
Handling platform differences
Preprocessor directives
Pushing code from Unity
Processing assets
Processing the build
Building your assets
Packaging gotchas
Distributing to mobile
Social network integration
Monetization
Paid
Paid with trial
Ad supported
In-app purchases
In-game currency
Going further
Summary

Mastering Unity 2D Game Development - Second Edition

Mastering Unity 2D Game Development - Second Edition

Copyright © 2016 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 authors, 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: August 2014

Second edition: October 2016

Production reference: 1071016

Published by Packt Publishing Ltd.

Livery Place

35 Livery Street

Birmingham 

B3 2PB, UK.

ISBN 978-1-78646-345-6

www.packtpub.com

Credits

Authors

Ashley Godbold

Simon Jackson

Copy Editor

Sameen Siddiqui

Reviewer

Claudio Scolastici

Project Coordinator

Ulhas Kambali

Commissioning Editor

Amarabha Banerjee

Proofreader

Safis Editing

Acquisition Editor

Smeet Thakkar

Indexer

Rekha Nair

Content Development Editor

Prashanth G

Graphics

Kirk D'Penha

Technical Editor

Sushant S Nadkar

Production Coordinator

Aparna Bhagat

About the Authors

Dr. Ashley Godbold is a programmer, game designer, artist, mathematician, and teacher. She holds a Bachelor of Science in Mathematics, a Master of Science in Mathematics, a Bachelor of Science in Game Art and Design, and a Doctor of Computer Science in Emerging Media, where her dissertation research focused on educational video game design.  She works full-time as a game developer and also runs a small indie/passion studio. She teaches college courses in Unity, 3ds Max, Adobe Flash, game design, and mathematics.

I would like to thank my husband, Kyle, and my daughter, Claire, for supporting me after I made the crazy decision to write a book and a dissertation at the same time. I would also like to thank my good friend, Danny Rich, for being the person with whom I initially set out to learn Unity and for helping me with character art in this book.

I'd also like to thank everyone at Packt Publishing for helping me through this process, particularly Smeet Thakkar, Prashanth G Rao, and Sushant Nadkar for all of their help through this process.

Simon Jackson has been a tinkerer, engineer, problem solver, and solution gatherer ever since his early years. In short, he loves to break things apart, figure out how they work, and then put them back together; usually better than before.

He started way back when with his first computer, the Commodore Vic20. It was simple, used a tape deck, and forced you to write programs in Basic or assembly language; those were fun times. From there, he progressed through the ZX Spectrum +2 and the joyous days of modern graphics, but still with the 30-minute load times from a trusty tape deck. Games were his passion even then, which led to many requests for another gaming machine, but Santa brought him an Amstrad 1640, his first PC. From there, his tinkering and building exploded, and that machine ended up being a huge monstrosity with so many add-ons and tweaked fixes. He was Frankenstein, and this PC became his own personal monster crafted from so many parts. Good times.

This passion led him down many paths, and he learned to help educate others on the tips and tricks he learned along the way; these skills have equipped him well for the future.

Today, he would class himself as a game development generalist. He works with many different frameworks, each time digging down and ripping them apart, and then showing whoever would listen through his blog, videos, and speaking events how to build awesome frameworks and titles. This has been throughout many generations of C++, MDX, XNA (what a breath of fresh air that was), MonoGame, Unity3D, The Sunburn Gaming Engine, HTML, and a bunch of other proprietary frameworks—he did them all. This gives him a very balanced view of how to build and manage many different types of multiplatform titles.

He didn't stop there as he regularly contributed to the MonoGame project, adding new features and samples, and publishing on NuGet. He also has several of his own open source projects and actively seeks any new and interesting ones to help with.

By day, he is a lowly lead technical architect working in the healthcare industry, seeking to improve patients' health and care through better software (a challenge to be sure). By night, he truly soars! Building, tinkering, and educating while trying to push game titles of his own. One day they will pay the bills, but until then, he still leads a double life.

I would like to thank my family above all, my wife, Caroline and my four amazing children (Alexander, Caitlin, Jessica, and Nathan), for putting up with me and giving me the space to write this title as well as my other extravagances—they truly lift me up and keep me sane. They are my rock, my shore, my world.

I would also like to thank Jamie Hales of PixelBalloon who generously donated some content for the Appendix and gave me new ideas and insights to look into.

A big shout out to all the guys who ran and helped me out with the Unity porting events, which I supported throughout the course of this book, namely Lee Stott, Simon Michael, Riaz Amhed, Louis Sykes, Ben Beagley, Josh Naylor, Mahmud Chowdhury, and Michael Cameron. Also, the Unity evangelists who were badgered throughout the events and were pumped for hidden details: Joe Robins and Andy Touch. Truly a great crowd to get game developers energized and their titles onto as many platforms as possible. Lots of weekends lost to writing, but the book was better, for they led to so many different experiences.

Finally, thanks to the reviewers of this title who kept me grounded and on target, although that didn't help to keep the page count low—thanks for your support guys.

About the Reviewer

Claudio Scolastici is a game designer with a background in Psychology, Cognitive Science and AI. He is currently a game designer for the video game and VR/AR developer SpinVector, author of cool games such as From Cheese and Artusi Cooking Time.

He is also a guest tutor at Digital Tutors/Pluralsight and a book author for Packt.

www.PacktPub.com

eBooks, discount offers, and more

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

Preface

The Unity engine has revolutionized the gaming industry, by making it easier than ever for indie game developers to create quality games on a budget. Hobbyists and students can use this powerful engine to build 2D and 3D games, to play, distribute, and even sell for free! Unity 4.3 dramatically reformed the way developers could create 2D games when they included sprite rendering, 2D physics, and sprite key-frame animation. Unity 4.6 further shook the gaming world by adding a new and elegant UI system that perfectly complimented the 2D games developers began creating. Now, Unity 5 has arrived! And this text will explore all the wonderful features it has to offer for 2D game development.

In this book, you will learn how to build an RPG game framework, learning lots of tips and tricks along the way. You will start by making a character and a village for the character to interact with NPCs. Then you will develop an overworld map for the character to explore that will be loaded with enemies who randomly attack her. After that, you'll cover the process involved in setting up a turn based battle system along with all of the necessary steps for creating a functional GUI. Following that, you'll develop a shop and inventory system and then implement sound and music. By the end of this book, you will be able to architect, create, deploy, your game as well as have the knowledge to build and customize the Unity editor.

What this book covers

Chapter 1, Overview. This chapter gives a basic overview of the 2D features provided within Unity 5. It also provides general guidance for finding free assets to use within 2D projects. Lastly, it points out key differences between Unity 5 and Unity 4.

Chapter 2, Building your Project and Character. This chapter covers the steps necessary to start building a project. It describes object oriented programming, how it is used in Unity, and the basic structure of a class in C# using MonoDevelop. This chapter also describes the process of importing, editing, and implementing, 2D sprites into the Unity engine, as well as the programming required to move the sprite around the screen with the player's interaction.

Chapter 3, Getting Animated. This chapter introduces animation in Unity by utilizing the various animation components. It describes the process of converting a sprite sheet to an animation clip and implementing the Animator component. It also describes the process of setting up the Animator Controller and explains how to implement animation parameters using scripting.

Chapter 4, The Town View. This chapter explains the process of setting up the town in which the character will walk around. It also explains the process of working with the camera and how to program the functionality necessary for the character to interact with her environment.

Chapter 5, Working with Unity's UI System. This chapter gives a general overview of the UI system implemented in Unity 4.6.

Chapter 6, NPCS and Interactions. This chapter covers the overall structure of interacting with non-player characters within an RPG. It then describes the process of writing and implementing the code necessary to allow the player to speak with the NPCs, and displaying the conversation utilizing the UI system.

Chapter 7, The World Map. This chapter discusses the process of building a map for the player to navigate and allowing the player character to exit the initial town.

Chapter 8, Encountering Enemies and Running Away. This chapter discusses the process of creating a battle scene that contains randomly spawning enemies. It then covers the programming required to have the player character transition in to random battles and transition back to the map by selecting the option to run away.

Chapter 9, Getting Ready to Fight. This chapter discusses the process of developing a battle introduction animation and the GUI that will allow the player to interact with the battle.

Chapter 10, The Battle Begins. This chapter further develops the battle system, by implementing the code that allows the player to select various attacks, incorporating particle systems to represent attacks, and utilizing an event system.

Chapter 11, Shopping for Items. This chapter discusses the process of creating a shop in which the player can buy items and an inventory system in which the player can save the purchased items.

Chapter 12, Sound and Music. This chapter covers the basics of sound integration utilizing audio listeners and sources, by adding background music and a sound effect when the player purchases an item.

Chapter 13, Putting a Bow on It. This chapter covers the finishing touches necessary to create a complete game. This includes packaging the game, implementing a splash screen and menu system, extending the editor, and adding a system to save the player’s data.

Chapter 14, Deployment and Beyond. This final chapter discusses how to convert the final game to a playable game.

What you need for this book

In order to follow this book, you will need the Unity game engine available at https://unity3d.com/get-unity/download.

You will need to download version 5.3 or higher. This text was written using 5.3.4. If for some reason, you want to get Unity 5.3.4 instead of the most recent version, you can get archived versions from https://unity3d.com/get-unity/download/archive.

To get the art assets and code discussed within the book, you should download the book's support files.

Who this book is for

This book is intended for anyone looking to get started in developing 2D games with Unity 5 or anyone already familiar with Unity 2D wishing to expand or supplement their current Unity knowledge. A basic understanding of programming logic is needed to begin learning with this book, but intermediate and advanced programming topic are explained thoroughly so that coders of any level can follow along. Previous programming experience in C# is not required.

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.

You can also download the code files by clicking on the Code Files button on the book's webpage at the Packt Publishing website. This page can be accessed by entering the book's name in the Search box. Please note that you need to be logged in to your Packt account.

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/Mastering-Unity-2D-Game-Development-Second-Edition. 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/MasteringUnity2DGameDevelopmentSecondEdition_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. Overview

Arguably, the most important parts of any project are knowing where to start and what tools you have in your arsenal before setting out to make your game. In this chapter, we will give a brief overview of the 2D tools offered in Unity 5 and explore the new features available to Unity 5.

Since this is the first chapter, let's cover how this book is structured. The main aim of this book is to build a fully functional, retro-style, Role-Playing Game (RPG) framework and cover all the main aspects of any good and well-rounded RPG game, including the following features:

Character development and setupBuilding your main game viewA wider world viewEvents and encountersShopping and inventory systemsBattles

We will be visiting places such as the following:

Your home town, as shown in the following screenshot:
The local shop, as shown in the following screenshot:
The outside world, as shown in the following screenshot:
Battling dragons in the dark forest, as shown in the following screenshot:

In this chapter, we will walk through the key terms used when working in 2D, as well as the big changes made in Unity 5 relevant to 2D game creation. We will kick off the next chapter by building the foundations of our project with some of the best practices in the industry, including guidance from the Unity team themselves (either direct from team members or from responses in the forums).

The following topics will be covered in this chapter:

Overview of Unity's 2D systemRundown of new features provided in Unity 5

Getting assets

Since creating games can become quite expensive, we'll use some of the best free assets out there. There are plenty of resources available to game developers, either as placement assets for the developer's use, whether they are full assets, or just a framework that you can tweak to get your desired result. There are a multitude of options.

Note

In the code bundle of this book, you'll get all the assets you need to follow during the creation of the game. The site where it is available online will be listed with the instructions.

Some of the best sites to gather assets are described as follows:

Art: Art, especially 2D art, is generally easy to find on a budget, particularly for the placeholder art, until you buy or create your own for the finished product (although I've seen many games created with some of these assets). Some good sites to start with are http://opengameart.org/ and http://open.commonly.cc/.Audio: Sound that works for your project is a lot trickier to get. Free sites are okay, but they generally don't have the right sound you will want or you will end up digging through hundreds or more sounds to get a close match. A good website to start with is http://soundbible.com/.General: Some sites just hold a general collection of assets instead of specializing in specific areas. The best site for this, as everything is almost guaranteed to be free, is http://search.creativecommons.org/. The Unity Asset Store also offers a great deal of free assets from art to code. Some of these assets are available from users, and others are available from the Unity team themselves. Not all of the assets are free, but you can easily sort your search result by price. You can find the Unity Asset Store at https://www.assetstore.unity3d.com.

Unity's 2D features

In 2013, with the release of Unity 4.3, Unity made 2D game development significantly simpler by adding native support for 2D development to the Unity editor environment. Since then, 2D game development has been on the rise among the indie and hobbyist developers. This section will give a general overview the various 2D features and terms as they appear in Unity 5.3.

2D mode versus 3D mode

When creating a new Unity project, you can choose between 3D mode and 2D mode, as shown in the following screenshot:

The main differences in the two modes are the way assets will be imported into your project and the default camera view and position. If you select 2D, the default camera will be set to Orthographic projection, the camera's position will be set to (0, 0, -10), your scene will be in 2D view, and your and images will be imported as sprites rather than textures.

You can easily swap between the two modes at any time during development by navigating to Edit | Project Settings | Editor and changing the Default Behavior Mode option, as shown in the following screenshot:

Changing the Default Behavior Mode will not affect how your game runs. This setting really only makes the process of importing new assets and creating new cameras quicker, because you will not have to manually change the texture type of images and change the projection of camera.

Note

There are a few other items that are handled differently in 2D mode versus 3D mode, such as lighting, and you can find a list of all the differences at http://docs.unity3d.com/Manual/2DAnd3DModeSettings.html.

Working with sprites

Sprites are 2D images. Sprites can be images that depict a single object (for example, a character) or an entire scene (for example, a background). Several sprites can also be combined to create a single object, as shown in the following screenshot:

A character created by combining multiple sprites; example from Unity's platformer sample

When your project is set to 2D mode, any image you import in to your project folder will automatically be assigned a Sprite (2D and UI) texture type. This means that the image is assumed to represent a 2D object or scene rather than an image that will applied to a 3D object.

When a sprite image is dragged from the Assets folder to the Scene view, a 2D Object-Sprite will be added to your scene. This object will automatically be given the Sprite Renderer component (refer to the following section), making the sprite visible in your game; no additional lighting or work is required.

Note

It's important to note that if your sprite has transparencies, you want to import your sprite texture as a .png formatted image file.

By default, each image is imported as a single sprite; however, by using the Sprite Editor (refer to the Sprite Editor section), you can change this in various ways.

Note

While your sprite textures can be any dimension, it is highly recommended that the texture be a perfect square with a power of two pixel height and width (that is 64 px by 64 px, 128 px by 128 px, and so on).

Sprite Renderer

The Sprite Renderer is the component that allows a 2D object to be displayed as a Sprite on the screen. Refer to the following screenshot:

The Sprite property selects the image that will be displayed. Any image that is assigned a Sprite (2D and UI) texture type can be placed in this property. The Color property allows you to change the vertex color of the rendered image as well as the transparency (through the alpha).

Flip is a property new to Unity 5.0. This will allow you to flip the sprite in the X or Y planes without having to use Scale properties in the transform, as was necessary in previous versions of Unity.

The Sprite Renderer component automatically sets the Material property of the object to Sprites-Default, which uses the default Shader property as Sprite/Default. The Sprites/Default shader does not interact with lights in the scene, so lights are not required to view Sprites with these default settings.

Sprite Editor

The Sprite Editor allows you to manipulate a sprite once it has been imported in to Unity. The Sprite Editor is only available for graphics with Texture Type set to Sprite (2D and UI). The following is the screenshot of the Sprite Editor window showing a single sprite:

The editor allows some basic manipulations to happen to a sprite, for example:

Changing the sprite's pixilation (mipmap)Altering the sprite's pivot positionSplicing the texture to identify the sprite region (this is also used for sprite sheets; refer to the next section)

Sprite sheets

Sprite sheets are a core part of any 2D animation system. Sprite sheets are a single texture that contains multiple images that represent individual frames of a 2D animation. Unifying all textures into a single larger texture means greater performance when sending the sprites to the graphic cards, which is a lot faster than sending lots of smaller files. Refer to the following screenshot:

Sprite Editor window showing multiple sprites in a grid

The traditional way of forming sprite sheets is to put sprites into specific regions on a single image and then identify the box regions where the individual sprites lie. These regions form individual frames in the sprite animation. As you can see in the preceding screenshot, nine sprites are arranged in three rows to form a character's walking animation. The sprites could have also been arranged in a single row or a single column; it doesn't matter. It's just how the artist best packs the sprite sheet for the animation. Unity can handle just about any arrangement you wish to throw at it. Just set the width and height of each texture region and the Unity Sprite Editor will do the rest. If your individual sprites are non-disjoint images, all of the same size, Unity can also automatically slice the texture in to the appropriate regions.

Texture atlases

Akin to sprite sheets, texture atlases are a more efficient way of packing textures into a single texture. It can contain various parts of a character (as follows), or a set of weapons, or a set of buttons to be used in your UI—anything really.

A selection of separate textures that have been automatically packed; example from Unity's platformer sample

Unity has added a very clever texture cutting and edge detection to make this work very well and identify specific regions on the texture for each sprite. You can also change the selection areas if Unity is too optimistic when selecting the texture regions.

The Sprite Packer utility provided by Unity can combine all of your sprite textures in to a single tightly packed atlas to help improve the performance of your game.

Physics 2D

The inclusion of a 2D physics system in Unity 4.3 has made 2D game creation easier than ever. Before the inclusion, these physics had to be either programmed by the developer or faked using 3D physics. However, now, with the use of the RidgidBody2D component, the various 2D colliders, physics materials, effectors, and joints, making a 2D game with physics can be achieved with a few simple clicks.

Note

Physics plays an important role in many 2D games. This is particularly true for platformers and certain puzzle games such as Tsum Tsum, Angry Birds, and Cut the Rope.

The RigidBody2D component can be added to any object that you want to be affected by the physics engine. For example, you can add the RigidBody 2D component to a sprite you want affected by gravity. The various 2D colliders, such as the Box Collider 2D and Polygon Collider 2D, can be added to any object that you want to check collision on. This can be used to keep objects from passing through one another (refer to the following screenshot) or can be used to check when two objects touch each other.

Example of 2D colliders used in the Unity platformer to surround walkable elements

You can also apply physics materials to your 2D objects using Physics Material 2D. This allows greater control over an object's physics interactions, such as friction and bounciness.

An effector is essentially a component that applies a type of force to sprites that interact with the 2D object that has an effector component attached to it. Unity 5 added four effector components to the Physics 2D library: Area Effector 2D, Point Effector 2D, Platform Effector 2D, and Surface Effector 2D. When Unity 5.3 released, the Buoyancy Effector 2D component was added. Constant Force 2D was also included in the Unity 5 update, which allows you to apply a constant force to a sprite.

Joints are also included in the Unity Physics 2D package. Joints allow various 2D game objects to join together in distinct ways. Four new joints were added with Unity 5.3. There are nine joints now included in Unity: Distance Joint 2D, Fixed Joint 2D, Friction Joint 2D, Hinge Joint 2D, Relative Joint 2D, Slider Joint 2D, Spring Joint 2D, Target Joint 2D, and Wheel Joint 2D.

Changes to Unity 5

If you have been working with Unity 4.x and are now starting out in Unity 5.x, there are a few key differences in the way things behave. Here you will find a general overview of the most relevant changes to 2D game development, other than the ones already discussed concerning 2D physics.

Note

The following list does not include all of the new features included in Unity 5 and the Unity 5.3 update. For a complete list, visit http://unity3d.com/unity/whats-new/unity-5.0 and http://blogs.unity3d.com/2015/12/08/unity-5-3-all-new-features-and-more-platforms/.

Licensing

Let's start with the best new feature of Unity 5. In previous versions of Unity, certain features were only available in the Pro version and were blocked in the free version. However, in Unity 5, all features are unlocked and can be enjoyed even by developers using the free version, now named Unity Personal. If a game you create with Unity Personal makes $100k or more, you will have to pay for the professional version.

Component access

Another big change to Unity 5 is the removal of quick property accessors within code. This means that a lot of your code written for Unity 4 will need to be rewritten. For example, the use of .rigidBody2D and .collider2D are no longer permissible. However, if you have code in your game from an older version of Unity, you will be shown the following warning:

Selecting I Made a Backup. Go Ahead! will automatically convert all quick property accessors to code containing the GetComponent function. For example, take the following code that was previously written as:

object.ridgidBody2D.isKinematic=false;

Now the preceding code would now be written as follows:

object.GetComponent<Rigidbody2D>().isKinematic=false;

Note

Make sure you back up your code before selecting, I Made a Backup. Go Ahead! The automatic changes may not be what you expect.

Animator changes

The most glaring difference when you initially start up the Unity 5 Animator will be the inclusion of an Entry node. Unity 5 has now added Entry and Exist nodes to StateMachines (we will discuss state machines in Chapter 8, Encountering Enemies and Running Away). These nodes allow the transition between states machines. For the most part, you animations that were running in Unity 4 should run appropriately in Unity 5, but will include the new Entry node, as shown in the following screenshot:

StateMachine Transitions with Entry and Exit nodes provided by Unity

Audio mixing

Previously, if you had a lot of audio sources in your game, dealing with all of them could be quite a hassle. Unity 5 provide an Audio Mixer asset type that now allows you to adjust all of your audio levels more efficiently, as show in the following screenshot:

Audio Mixer image provided by Unity

Summary

2D game development has received a new life with the inclusion of 2D support in Unity 4.3. Since then, many other features have been added, making Unity 5.3 one of the most versatile and user-friendly gaming engines on the market. Never before has it been easier to make a 2D game from start to finish on a budget and within a short amount of time.

In this chapter, we covered the objective of the book, the paths to get the assets needed for the sample project, an overview of the key terms and features related to 2D game development in Unity, and an overview of the most apparent changes implemented in Unity 5 related to 2D game development.

Are you sitting comfortably? Well, keep your arms and legs in the ride at all times and prepare yourself for a high-speed ride!

Chapter 2.  Building Your Project and Character

It's time to start putting the building blocks that will make up your game into Unity. We will start with setting up the project and then move on to building the main character. Setting up the main character is an important first step, as most of your game's core logic and framework generally centers on the main protagonist and highlights exactly how the player will interact with the game.

We will be creating two main locations for the character to explore: a 2.5D town in which she can interact with Non-Playable Characters (NPCs) and a world map in which she will encounter and battle enemies. To allow our character to interact with and explore these locations, we must first get our character into our project and give her the ability to move around the scenes. We must also get our project started the right way by setting up the project appropriately.

The following topics will be covered in this chapter:

Designing a good project structureCreating a project and scenesImporting SpritesWorking with classes and componentsPlanning and designing behaviorsSetting up user control effectively

Project overview and structure

Before you start your project, you should consider how you intend to set it up and architect your project in the long term. Far too many developers have created problems for themselves by just diving in rather than designing the outline for the project at the start.

Your game and your assets are not the only things to consider when starting a fresh project. Sure, you can start importing assets, creating scripts, and getting things running; most Proof of Concept (POC) projects start this way. Once your project is of a sufficient size and you start expanding on your initial concept, you'll realize that you have issues with regard to picking up items and putting them together. Then, you will start devising new ways to organize your project and eventually find that it's an unmanageable mess; nevertheless, you will stride on, taking longer and longer to produce new content or add new features.

The best advice one can give is to think about your entire project and how you organize it as an asset in itself, and accordingly, design it correctly from the beginning. So, what follows are a few short tricks that you can learn to get started on the right foot.

Architecture is a point that is often missed out in game development and should not be overlooked. What follows are some of the best practices you can use from day one to design your game and thereby save a lot of time to fix or change and reorder things later. These lessons will be used throughout the course of this book, wherever applicable.

Project overview

Before we can start discussing how to structure our game's project, we need to discuss what features the game we will be creating will actually include.

We will be creating a 2D RPG with the following key attributes:

A 2.5D townA conversation systemA shop with an inventory systemA character inventory systemA top-down overworld with random encounter battlesA turn-based battle system with character animations

Now that we have a general idea of what type of game we will be creating, we can start structuring our project and implementing some if its features.

Structure

When you start a new Unity project, Unity places the Assets folder within the folder you designate for the project. Many Unity projects have all their assets in the root Assets folder or are organized by how the game works. This isn't particularly wrong, but as the project gets larger, this will eventually cause problems.

The best way in which Unity advises you to organize your project (as also shown in all of their own examples) is to group objects by their type in the root Assets folder, as shown in the following screenshot:

This ensures that you will find assets for your entire project that are ready for reuse in every scene or level according to the type of object. You can then subdivide these appropriately depending on their use, such as the following:

Separating animation clips from all the controllers that may act on them or on your models:
Grouping audio by its intended use in your game, such as enemies, special effects, and background music:
Grouping prefabs by layer or their intended use:
Sprites can also be structured in the same way; you can order them according to how they should be used in your project:

By following the preceding patterns, you are organizing your project effectively in the same way Unity does and guiding yourself to use a more component-based design. Each scene is built up of many assets through the lifetime of your project, so organizing your assets this way will help in the long run.

You can set this level of subgrouping for scripts, scenes, fonts, materials, and so on. However, as these are generally distinct things that apply to every asset, there is no need to divide them further.

Asset naming

There are no specific patterns for how you should name each of your assets. Generally, this is left to your preference and, more importantly, how you recognize each part of your game. There is no need to give something a really long and complicated name in the preceding structure, only so long that you can find it later.

While it is not required that you follow a naming pattern, some of the more common patterns include the following:

Prefixing the name with a three letter acronym for its type: scn for a scene, efx for an effect, and so onSuffixing an underscore plus the same three letter acronym to the end of an asset's nameUsing a path-like name such as PlayerScene1BounceToWallScript

From experience, these are useful, but my advice is to name things plainly based on what it is. Using the structure mentioned earlier, you have already organized your assets to overcome a lot of the issues that the preceding patterns try to solve.

Plan ahead before you even start your game and set a standard that works for you. You should be able to identify what each asset is and what it does just by looking at the name. However, remember that each asset will most likely be used many times on many different game objects, so plan accordingly. Add prefixes and suffixes only when a script or asset is intended to be limited to a certain type of game object.

The Unity examples are another good place to look for inspiration here. See the following screenshot and decide whether you can tell what these scripts are and what they are used for just by looking at them:

Unity script examples

Creating the project

Before you can start building the game in Unity, you need to start a new project. Select New at the top of Unity's Home Screen. When creating a 2D game, you want to ensure that you start the project in 2D mode by selecting the appropriate mode in the Unity's home screen, as shown in the following screenshot:

Unity's home screen

Note

Remember, if you accidentally set the mode to 3D, you can change this at any time for your project through Editor Settings, as discussed in the previous chapter.

After selecting Create project, you'll be brought to the Editor Window, as shown in the following screenshot:

Unity's Editor window

It's important to note that when you create a new project in Unity, you are creating a new folder that can be accessed through File Explorer (Windows) or the Finder (Mac OS X) with the following subfolders:

Now that we have created our project, let's create the folder structure for the project, as shown in the following screenshot and discussed previously:

To create a new folder from within Unity, simply select Create | Folder from the project tab in the bottom left corner of the screen:

When creating folders from within Unity, they will be represented within the Assets folder saved to your computer. Alternatively, if you create the folders from within Window's File Explorer (or Mac's Finder), the folders will appear within Unity. In the following screenshot, you will see how the folder structure is mirrored between Unity's Project window and Window's File Explorer:

Unity's Project windows and Window's File Explorer

As you can see, these folders created from within Unity are showing up in our project folder saved to our computers.

Note

At this point, it's important to note that we will most likely not use all of these folders during the course of this book. Nevertheless, it is a good working practice to get these folders set up for every project just so that you have a standard template.

Creating a scene

Every level or distinct area you create within Unity will be an individual scene. So, the start screen will be a scene, the town will be a scene, the map will be a scene, and so on.

We will have the following scenes in our game:

Start ScreenTownShopOverworldBattle Scene

When you start a new project in Unity, you will be given a blank scene that contains only a camera, as shown in the Hierarchy in the following screenshot:

Tip

The Hierarchy displays a list of all the objects within a scene.