Home Game Development Mastering Unity 2D Game Development - Second Edition

Mastering Unity 2D Game Development - Second Edition

By Ashley Godbold , Simon Jackson
books-svg-icon Book
eBook $39.99 $27.98
Print $48.99
Subscription $15.99 $10 p/m for three months
$10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime!
What do you get with a Packt Subscription?
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
BUY NOW $10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime!
eBook $39.99 $27.98
Print $48.99
Subscription $15.99 $10 p/m for three months
What do you get with a Packt Subscription?
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
  1. Free Chapter
    Overview
About this book
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!
Publication date:
October 2016
Publisher
Packt
Pages
506
ISBN
9781786463456

 

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 setup

  • Building your main game view

  • A wider world view

  • Events and encounters

  • Shopping and inventory systems

  • Battles

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 system

  • Rundown 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 position

  • Splicing 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 2DTarget 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!

About the Authors
  • Ashley Godbold

    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 also authored Mastering Unity 2D Game Development: Second Edition (Packt Publishing) and the first edition of Mastering UI Development with Unity. In her free time, she enjoys playing video games and watching anime with her husband, daughter, three cats, and dog.

    Browse publications by this author
  • Simon Jackson

    Simon Jackson is a long-time soft ware engineer and architect with many years of Unity game development experience, as well as an author of several Unity game development titles. He loves to both create Unity projects and lend a hand to help educate others, whether it's via a blog, vlog, user group, or major speaking event. He currently works at a mixed-reality research lab called xRealityLabs, building the future of digital solutions for the construction and medical industries. His primary focus at the moment is on the Reality Toolkit project, which is aimed at building a cross-platform mixed-reality framework to enable both VR and AR developers to build efficient solutions in Unity.

    Browse publications by this author
Latest Reviews (4 reviews total)
Highly satisfactory book and video on Unity for 2D games
Nice balance and content. Not so "Mastering", but a beginner's kind of book. But I really enjoyed and learnt a lot with this one.
Excelente libro para comenzar en el mundo Unity
Mastering Unity 2D Game  Development - Second Edition
Unlock this book and the full library FREE for 7 days
Start now