Home Game Development Mastering Android Game Development with Unity

Mastering Android Game Development with Unity

By Wajahat Karim , Siddharth Shekar
books-svg-icon Book
eBook $32.99 $22.99
Print $41.99 $24.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 $32.99 $22.99
Print $41.99 $24.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
    Introduction to Android Game Development with Unity3D
About this book
Game engines such as Unity are the power-tools behind the games we know and love. Unity is one of the most widely-used and best loved packages for game development and is used by everyone, from hobbyists to large studios, to create games and interactive experiences for the Web, desktop, mobile, and console. With Unity's intuitive, easy-to-learn toolset and this book, it's never been easier to become a game developer. You will begin with the basic concepts of Android game development, a brief history of Android games, the building blocks of Android games in Unity 5, and the basic flow of games. You will configure an empty project for the Jetpack Joyride Clone Game, add an environment and characters, and control them. Next you will walk through topics such as particle systems, camera management, prefabs, animations, triggers, colliders, and basic GUI systems. You will then cover the basic setup for 3D action fighting games, importing models, textures and controlling them with a virtual on-screen joystick. Later you will set up Scene for 3D Configuration, create basic gameplays, and manage input controls. Next you will learn to create the interface for the main menu, gameplay, game over, achievements, and high score screens. Finally you will polish your game with stats, sounds, and Social Networking, followed by testing the game on Android devices and then publishing it on Google Play, Amazon, and OUYA Stores.
Publication date:
May 2017
Publisher
Packt
Pages
352
ISBN
9781783550777

 

Chapter 1. Introduction to Android Game Development with Unity3D

In today's era of smartphones, which once was the era of computers, almost everyone on the planet is holding a smartphone in their hands. About 1 billion Android phones have been sold in 2014, which is a huge audience for developers who work on Android. These developers put their effort into creating high utility apps, which solves the problems of their users or addicting and fun games and allows players to pass the time having fun and enjoying good interactive experiences. This book is mainly focused on covering the latter part, creating addictive fun games, by using a very famous game engine called Unity3D.

This chapter includes the following topics.

  • Introduction to Android
  • Unity3D and Game Engines
  • Basics of Unity Game Development
  • Configuration of Empty Game Projects
  • Starting the Perky Penguin Game
  • Adding the Penguin to the Game

 

 

 

Introduction to Android


Android is a Linux-based operating system, which makes it open source software distributed under the Apache License Agreement by Google Inc. Due to its open source nature, other phone vendors have started porting the Android operating system on their newly created phones, which contributed to a very varied smartphone market for consumers. Starting from the first version of Android, this operating system has gained a good level of maturity, making it more reliable, secure, and stable operating system for smartphones. Let's have a look on some popular versions of Android in the next section.

Android versions

Year by year, Android has increased its maturity level with each new version. Every version introduced new set of features from the user interface to customizations to flexibility to security. In terms of names, these versions are based on names of candy, chocolates, and other sweet stuff, such as Kitkat, Lollipop, and Marshmallow, but that's what makes Android a little more understandable to consumers and developers as well.

Note

It is an interesting fact that the versions of Android are in alphabetical order. Starting off from Apple Pie 1.0 and then Banana Bread 1.1, it made its way towards Nougat with a completely coherent of alphabetical sequence maintaining the legacy.

The following table highlights the main features of the different Android versions with their API levels as well:

Android version

Version name

Main features

API level

Release month

1.0 G1

Banana Bread

GPS, Bluetooth, Multitasking, Google Services, Android Play Store

2

February 2008

1.5

Cupcake

Search Box, Revamped Android Play Store, Camera, Gestures

3

April 2009

1.6

Donut

Onscreen Keyboard, Home Screen Widgets, Folders

4

September 2009

2.0.x

Éclair

Multiple User Accounts, Flash Support, Zoom Feature, Bluetooth 2.1

5, 6, and 7

October 2009

2.2.x

Froyo

USB tethering, Hotspot support, Adobe Flash, Voice Dialling

8

May 2010

2.3.x

Gingerbread

New Copy/Paste, WebM, NFC, Front Camera

9, 10

December 2010

3.x

Honeycomb

3D Graphics, Redesigned UI, Video Chatting, Bluetooth tethering, 3G, 4G

11, 12, and 13

February 2011

4.0.x

Ice Cream Sandwich

Virtual buttons, Face Unlock, Native Camera Features, Face Detection, Android Beam, Wi-Fi Direct

14 and 15

October 2011

4.1 - 4.3

Jelly Bean

Expandable Notifications, Google Now

16, 17, and 18

July 2012

4.4

Kit Kat

Major Design Interface Update, Translucent Status bar, Immersive Mode, Wireless Printing

19 and 20

October 2013

5.0

Lollipop

Redesigned UI with Material, Lock Screen Notifications, Guest mode, Battery Saver mode

21

October 2014

6.0

Marshmellow

Fingerprint security support, Doze mode for battery saving, App standby mode, Enhanced App permission

23

October 5, 2015

7.0

Nougat

Multi window view, VR support

24, and 25

August 22, 2016

Table 1.1: Era of operating systems from Android Cupcake to Lollipop

The table only shows the changes made by Android operating system's developer, Google Inc. But due to Android's open source nature, other mobile manufacturing companies have also changed and introduced new features and modifications into Android. For example, Samsung has made a custom touch interface called TouchWiz, and HTC has made a custom user interface called HTC Sense. Similarly, Sony has introduced a custom user interface called TimeScape.

Figure 1.1 Latest Android phones launched in year 2014

Google Play - the market store for Android

After the introduction of smart phones, the concept of market store came to existence in software technology, which revolutionized the mobile development industry. A significant role was played by Google Play in that revolution of mobile apps and games. Google Play is the largest market store in smartphones, with more than 2.2 million Android apps, games, books, music, shows, and more. These apps and games have been downloaded more than 50 billion times up to this point, and that marks a huge milestone achieved by Google in just 8 years of Android. You can check out Google Play at http://play.google.com.

Note

Google Music, Google Movies & TV, Google Books, and Google Magazines are available in only limited countries.

Figure 1.2 Google Play on an Android device

 

Unity3D and game engines


A game engine is a software framework designed for the creation and development of video games. Many tools and frameworks are available for game designers and developers to code a game quickly and easily without building from the ground up. As time passed by, game engines have become more mature and easy for developers, with feature-rich environments. Starting from native code frameworks for Android such as Unity, Unreal, Cocos2D-x, LibGDX , and so on, the game engines started providing clean user interfaces and drag-drop functionalities to make game development easier for developers. These engines include lots of the tools which are different in user interface, features, porting, and many more things but all have one thing in common; that is they create video games at the end.

We will discuss some of the most popular game engines in this section by comparing those on the basis of:

  • User Interface and environment like how easy it is to learn and develop games.
  • Features and functionality like what game engine can achieve and do and on what level of quality.
  • Pricing like is it free or paid.

Let's get into more details with this comparison.

Unreal Engine

Unreal Engine (http://www.unrealengine.com) is a game engine developed by Epic Games. It was an in-house game engine of Epic Games and was first showcased in 1998 first person shooter game Unreal. Unreal Engine is mostly used for creating first-person or third-person shooter games but it has also shown quite good quality in other genres such as stealth, MMORPGs etc. Unreal Engine includes high degree of portability and easy interface features with more logic and behaviors written in C++ language.

The latest release called as Unreal Engine 4 supports almost all platforms supported by Unity including Windows, Xbox One, Windows RT, OS X, Linux, PlayStation 4, iOS, Android, Ouya, and browsers using WebGL.

Unreal Engine 4 was released in March 2014 for the public use. Unreal Engine has nice user interface and navigation controls are very polished and easy to use. Unreal Engine provides very easy flow and interface to create first person shooter games and contains features to produce AAA quality game including real-time global illumination using voxel cone tracing, eliminating pre-computed lighting.

You can download the engine and use it for everything from game development, education, architecture, and visualization to VR, film and animation. When you ship a game or application, you pay a 5% royalty on gross revenue after the first $3,000 per product, per quarter Unreal Engine's learning curve is a little high so it's not best suited for new aspiring game developers:

Figure 1.3 Unreal Engine 4 Interface

Adobe Flash professional

Adobe Flash (formerly called as Macromedia Flash) (http://www.adobe.com) is a multimedia and software platform used for creating vector graphics, animations, games, and rich internet applications (RIAs) that can be viewed, played, and executed in Adobe Flash Player. The Flash is widely used for creating animations and mostly advertisements for web browsers but its use of creating games is declined very heavily in recent years by HTML5 framework.

There was a time when Adobe Flash was most popular game engine for online browser games and made a quite big wave of independent game developers creating games for online portals such as Kongregate and Miniclip.

The Adobe Flash includes very easy interface to create amazing and robust animations allowing artists to create vector art directly in the editor. It also supports Adobe Illustrator and Adobe Photoshop layers as well to make it easy integrated with vector art and animations. Adobe Flash allowed developers to port their games and animations from browsers to Desktops (Mac and Windows), Android, and iOS using Adobe AIR framework but couldn't grasp the much attention of game developers and artists due to low performance on end devices.

Adobe Flash has a Free 30-day trial but once the trial is finished you must buy a license unlike other engines discussed in this section.

Figure 1.4 Adobe Flash CC Interface

Game Maker Studio

Game Maker Studio (originally names Animo and later Game Maker) is an event-driven game creation system created by Mark Overmars in Delphi programming language in 1999. Originally created for 2D animations, it quickly moved up high on to being a very robust and easy-to-use drag-drop tool for creating 2D games.

Game Maker Studio uses pre-defined events to create actions in the game, which makes it very easy for developers to create games without needing prior knowledge of programming and coding stuff. The tool comes with a sandboxed language called Game Maker Language (GML), which allows developers to define custom and more complex behaviors for their games.

The Game Maker Studio comes with a clean and slick user interface that lets developers build and deploy their games on Windows, macOS X, Ubuntu, HTML5, Android, iOS, Windows Phone 8, and Tizen. The latest version also introduced Xbox One and PlayStation deployment.

Note

Tizen is the open source operating system (OS) of everything, including mobiles, wearables, in-vehicle infotainment, and TV.

Figure 1.5 Game Maker Studio Interface

Unity3D

Unity (http://unity3d.com) is cross-platform game engine developed by Unity Technologies. It made its first public announcement at Apple's Worldwide Developers Conference in 2005 and supported only game development for Mac OS, but since then it has been extended to target more than 15 platforms for desktop, mobile, and consoles. It is notable for its one-click ability to port games on multiple platforms, including BlackBerry 10, Windows Phone 10, Windows 10, OS X, Linux, Android, iOS, Unity Web Player (including Facebook), Adobe Flash, PlayStation 3, PlayStation 4, PlayStation Vita, Xbox 360, Xbox One, Wii U, and Wii.

Unity has a fantastic interface that lets the developers manage the project really efficiently from the get-go. It has nice drag-drop functionality with connecting behavior scripts written in C# and Boo (a dialect of JavaScript) to define the custom logic and functionality with visual objects quite easily. Unity has been proven quite easy to learn for the new developers who are just starting out with game development and now more large studios have also started it using, and that is also for good reasons.

Unity is one of those engines that provides support for both 2D and 3D games without putting developers in trouble and confusion. It has vast collection of online tutorials, great documentation, and a very helpful community of developers. Also, Unity has the Asset Store, where developers sell reusable components of Unity to reduce the development time and efforts for other developers. You can check Unity Asset Store at http://assetstore.unity3d.com.

Unity Plus and Pro are available for a fee, and Unity Personal has no fee; it is available any use to individuals or companies with less than US $100,000 of annual gross revenue. For more information, visit the Unity store at https://store.unity.com/:

Figure 1.6 Unity3D Engine Interface

 

Features of Unity3D


Unity is a game development ecosystem of powerful rendering engine, intuitive tools, rapid workflows for 2D and 3D games, all-in-one deployment support, and thousands of already created free and paid assets with a helpful developers community. The feature list includes the following:

  • Easy workflow, allowing developers to rapidly assemble scenes in an intuitive editor workspace
  • Quality game creation, such as AAA visuals, high-definition audio, and full-throttle action, without any glitches on screen
  • Dedicated tools for both 2D and 3D game creation with shared conventions to make it easy for developers
  • A very unique and flexible animation system to create natural animations in very less time
  • Smooth frame rate with reliable performance on all the platforms developers publish their games
  • One-click ability to deploy to all platforms from desktops to browsers to mobiles to consoles, within minutes
  • Reduce the time of development by using already created reusable assets available on the huge Asset Store

In summary, compared to other game engines Unity is developer-friendly, easy to use, free for independent developers, and feature-rich game engine. In next section, we will see some amazing features of Unity3D.

 

Basics of Unity game development


Before delving into the details of Unity3D and game development concepts, let's have a look at some of the basics of Unity 5.6 We will go through the unity interface, menu items, using assets, creating scenes, and publishing builds.

Note

This section is required for all new developers who have very little or no knowledge of Unity and want to learn basics of game development using Unity. If you are already familiar with Unity basics, you can skip this section.

Unity editor interface

When you first time launch Unity 5.6, you will be presented with an editor containing a few panels on left, right, and bottom of the screen. There's nothing to worry from these panels. The following image shows the editor interface when it's first launched:

Figure 1.7 Unity 5 Editor Interface at first launch

First of all, take the time to look over the editor and become a little familiar with it. The Unity editor is divided into different small panels and views that can be dragged around, resulting in a workspace that can be customized, according to the developer/designer's needs. Unity 5 comes with some pre-built workspace layout templates that can be selected from Layout drop-down menu in the top-right corner of the screen, as shown the following screenshot:

Figure 1.8 Unity 5 editor layouts

The layout currently displayed in the editor is the Default layout. You can select these layouts and see how the editor's interface changes and how different panels are placed in different positions in each layout. This book uses the 2 by 3 workspace layout for the game. 

The following screenshot shows the 2 by 3 workspace with the names of the views and panels highlighted:

Figure 1.9 Unity 5 2 by 3 layout with views and panel names

As you can see in the preceding screenshot, Unity editor contains different views and panels. Every panel and view has a specific purpose, which is described in the following section.

Scene View

Scene View is the whole stage for the game development, and it contains every asset in the game from a tiny point to any heavy 3D model. Scene View is used to select and position environments, characters, enemies, the player, camera, and all other objects that can be placed on the stage for the game. All those objects, which can be placed and shown in the game, are called as GameObjects. The scene view allows developers to manipulate game objects such as selecting, scaling, rotating, deleting, and moving. In simple words, Scene View is the interactive sandbox for the developers and designers. The Scene View provides some controls, such as navigation and transformation.

Transform tools

While developing games in Unity, you will place lots of game objects in the scene and their position, scale, and rotations, collectively called as transforms, are managed by transform tools. The following screenshot shows the transform tools:

Figure 1.10 Transform Tools

You can select any selected transform action from this toolbar and change the game object accordingly. The following figure shows the gizmo on the selected game object when a transform tool is selected:

Figure 1.11 Gizmos on game objects of transform Tools

These tools do exactly the same job as their names suggest; move for translation, rotate for rotation, and scale for scaling. The Rect tool on other side was introduced in Unity 4.3 when Unity got native 2D support and tools. This tool is only for 2D sprite objects for their position, scale, and rotations. You can also select these tools with keyboard shortcuts.

Scene View navigation

In the last section, we discussed how GameObjects can be transformed and navigated in the scene. But Unity being a 3D environment, it has an easy interface to view the scene from different angles, sides, and perspectives using mouse and keyboard shortcuts. You can observe the Scene Gizmo in the top-right corner of the Scene view. This gizmo is used to rotate the view according to the developer's needs. The following screenshot shows the gizmo of the scene:

Figure 1.12 Scene Gizmo for Scene View Navigation

Every view of the scene is shown in either perspective or isometric. There is also another view for the scene which we will discuss in the next section.

Scene View control bar

The control bar is shown at the top of the Scene View and it gives the developer more control to navigate through their scenes and create games easily. This bar includes options such as enabling/disabling gizmos, sounds, and selecting view modes. The important part of this bar is the 2D mode button, as shown in the following screenshot:

Figure 1.13 control bar of Scene View

The 2D mode button is a toggle button; when turned on; it disables the z-axis of the view and show the game from 2D perspective. It is highly used option while creating 2D games in Unity. On the right side of the bar, there is a text box for search. This lets developers search the game objects from the current scene and allows them to quickly work.

Game View

The Game View is the final representation of how your game will look when published and deployed on the target devices, and it is rendered from the cameras of the scene. This view is connected to the Play Mode navigation bar at the top of the whole Unity workspace, as shown in the following screenshot:

Figure 1.14 Play mode bar

When the game is played in the editor, this control bar gets changed into blue. A very interesting feature of Unity is that it allows developers to pause the game and code while running and developers can see and change the properties, transforms etc at runtime without recompiling whole game for quick workflow.

Game View control bar

Like scene view, game view also includes a control bar on top side of the view as shown in the following figure:

Figure 1.15 Game View Control Bar

The options perform the actions as their names suggest. The Free Aspect drop-down on the left side of the bar lets developers choose any specific resolution to test their games. These resolutions and drop down options vary on the selected platform. Developers can also add their own custom resolutions and screen sizes for their targeted devices. Unity also allows developers to specify aspect ratios as well to have an idea of how the game will run on various devices with the same aspect ratio. Unity is quite powerful and easily gives cross-platform support to make their games run better on most types of devices writing code only once.

Hierarchy View

The Hierarchy View is the first point to select or handle any GameObject in the scene. This contains every game object in the current scene. This is tree-type structure allowing developers to utilize parent and child concepts on the game objects easily. The following screenshot shows a simple Hierarchy View:

Figure 1.16 Hierarchy View

Project browser panel

This looks like a view, but it is called the Project browser panel. This panel is an embedded files directory in Unity and contains all the files and folders included in the game project. 

Following screenshot shows a simple Project browser panel:

Figure 1.17 Project browser panel

The left side of the panel shows a hierarchical directory, while rest of the panel is the files or as these are called assets in Unity. Unity represents these files with different icons to differentiate these according to their file types. These files can be sprite images, textures, model files, sounds and so on. You can search any specific file by typing in the search text box. On the right side of search box, there are button controls for further filters such as animation files, audio clip files, and so on.

Note

An interesting thing about Project browser panel is that if any file is not available in the assets, then Unity starts looking for it on Unity Asset Store and presents you with available free and paid assets.

Inspector panel

This is a most important panel for development in Unity. Unity structures the game in the form of game objects and assets. These game objects further contain components such as transforms, colliders, scripts, and meshes, and so on. Unity lets developers manage these components of each game object through the inspector panel.

The following screenshot shows a simple inspector panel of a game object:

Figure 1.18 Inspector Panel

These components vary in type including physics, mesh, effects, audio, and user interface. These components can be added to any object by selecting it from the component menu. The following screenshot shows the Component menu:

Figure 1.19 Components Menu

After covering some of the basics of the Unity, let's move on to the very first task developers do when creating a game; and that is creating an empty project. Let's discuss the configuration of empty projects in Unity for 2D games in the next section.

 

Configuration of empty game projects


When you start a new game, the first step is to configure an empty game project. For 2D games, creating empty games and setting up the initial environment and camera management can sometimes become a painful process. In this section, we will discuss on how to configure empty game projects for 2D games.

Note

If you have already worked on 2D games in Unity, then you can skip this section and use the starter project of Perky Penguin from the code in the next section.

When you launch Unity 5.6, it shows a project wizard as shown in the following figure:

Figure 1.20  Project Creation Wizard

Unity has a nice and smooth user interface in its latest release, Unity 5.6. The project wizard shows a list of all the recent projects, along with their names. The most recent project is highlighted for quick opening. In the top-right side of the wizard, there are controls to create a new project from scratch and open any specific project from any directory. To guide new developers through basic concepts, the Get started tab offers a basic video tutorial.

Let's create new project by clicking on the New project button on top-right, and you will be presented with the following dialog box:

Figure 1.21 Project creation wizard

There are two text inputs, Project name and Location. Their names are self-explanatory. You will also notice 3D and 2D in the wizard, as shown in following figure:

Figure 1.22 Project type selection toggle

This toggle lets you tell Unity whether your project is 2D or 3D. Although this doesn't affect the project in any way while working on it, this affects default project setting for easier workflow. For example, in 3D mode, when you import any image asset into project, Unity will take it as a texture and in 2D mode, Unity will take it as a Sprite type. You can also change the mode later from the project anytime, it is not necessary to select at project creation time. By default, Unity will create project in 3D mode.

Along with 2D/3D mode, you will also notice the Asset packages... button at bottom on the project creation wizard. One of the best features of the Unity is the Assets support. Unity lets developers to create, distribute, and sell reusable plugins and add-ons called Unity Assets through Unity Asset Store available at http://assetstore.unity3d.com. Unity comes with a big collection of free assets to help you get some things done within the minutes. This button lets you choose which assets to import in the new project, shown as following:

Figure 1.23 Asset Packages Dialogue

You can select any package or multiple packages, and the new project will be created with those that have been already imported in it. For now, you don't need to import any packages. You can also import these later as you need it.

So, for the project creation wizard, we have named our project Perky Penguin and we have selected 2D mode. Click on the Create project button, and you will see the Unity interface with an empty scene and project.

The first step to follow is to make sure that you are in 2D or 3D mode. If you have selected 2D mode, then you will see 2D toggle active on the control bar in the Scene View, as shown in the following screenshot:

Figure 1.24 Control bar in Scene View

Also, you need to check in Editor Settings to make sure that the project is in 2D mode. You can do it by going to Editor Settings by selecting Editor option from Project Settings in the Edit menu as shown in the following figure:

Figure 1.25 Editor Settings Menu

On selecting the Editor option, you will see settings in the Inspector panel. Make sure that Mode in Default Behavior Mode is set to 2D, as shown in the following screenshot:

Figure 1.26 Editor Settings in Inspector Panel

You can also change it to 3D if you want Unity to interpret images as textures and enable other 3D settings by default. The last thing to make sure that the scene is in 2D mode, you need to check the camera properties. You may have already have noticed a Camera game object placed in the empty scene when creating a new project.

Select the Camera object and you will see its properties in inspector panel as shown in the following screenshot:

Figure 1.27 Main Camera Settings

You will notice that its Position will be set at (0, 0, -10) and its Projection setting will be as Orthographic.

Note

It is a good practice to use orthographic projection mode for 2D in unity.

Orthographic projection is a means of representing 3D objects in 2D. Orthographic views are commonly used in engineering as a means of producing object specifications that communicate dimensions unambiguously. For example, if you are looking at a larger scene with buildings then orthographic rendering gives a clear measure of distance between buildings and their relative sizes.

So, after making sure that the project is in 2D mode, let's save the scene. Unity project comes with a root directory of Assets, where all the assets used in project are placed. These assets can be scenes, scripts, textures, sprites, models, prefabs, or materials. There is no traditional or standard method of managing assets in Unity, and every developer has different methods. In this book, we will follow a simple method of managing assets. Our method of managing assets is to create different folders in the Assets directory for each type of resources. The following figure shows the directory structure in the Assets folder:

Figure 1.28 The Assets directory in Unity

After creating folders in Assets, let's save the empty scene with the configured camera in the Scenes directory with the name PerkyPenguin_GameplayScene.unity. Scene files have the .unity extension, and these files contain different game objects for camera, player, enemies, obstacles, environment, controls, and so on. Scenes are like different levels in the game. Any game can have one or more than one scenes and it is not necessary to create different scenes for each level. It is very important to note that all the scenes in the game should be added in Build settings in order to deploy them in the final package. We will discuss about deployment in more detail in the later chapters.

After saving the scene, we have only one thing left to fully configure an empty game project. That is configuring the game view so we can test our game. As this book is about Android game development, we have to set our project targeted to Android devices. Initially, the default target platform will be set to PC, iMac, and Linux standalone. You can see it in the Build Settings from the File menu as shown in the following screenshot:

Figure 1.29 Assets Directory in Unity

You will be presented with a dialog containing all the possible platforms to build game to and all the scenes included in the game, as shown in the following screenshot:

Figure 1.30 Build Settings

Select Android from the Platform list, and click on Switch Platform button and the project will be changed for Android devices. You might not notice anything after changing the target platform to Android but an easy way to check it is to see the resolutions list in the game view. You can do it by clicking on Free Aspect from the control bar in Game View as shown in the following figure:

Figure 1.31 Resolution List of Android Platform

In order to create a game, that runs on all Android devices, we have to select a primary target size for viewport implementation. We have chosen 1280x800 as our target device in landscape mode. We will discuss the cross-resolution approach in details in the later chapters.

You can also add your own custom resolutions by selecting the small plus button in resolution list. It will show you a dialog to put the size of resolution either in pixels or as an aspect ratio with its name. The window is shown in the following figure:

Figure 1.32 Add Custom Resolution in Game View

Finally, after setting the project in 2D mode and changing the platform to Android with our required resolution, we have only one little job remaining that is to configure camera according to our target resolution. Select the Main Camera from Hierarchy panel, and change the Size in Camera component to 3.2 as shown in the following figure:

Figure 1.33 Camera Size

So far, a 2D Unity game project has been created with an initial directory structure and an empty scene which include a 2D configured camera in it. In the next section, we will discuss on what game will be created in this chapter and how to create any game from scratch.

 

Perky Penguin game


This section is all about the game which we will create throughout this chapter and Chapter 2, Finishing the Perky Penguin 2D Game. Our game name is Perky Penguin and it is a Jetpack Joyride-based game. Final game of this chapter is shown as following:

Figure 1.34 Perky Penguin Gameplay

Perky Penguin is inspired from Jetpack Joyride game. Jetpack Joyride is a 2011 side-scrolling endless runner and action video game created by Halfbrick Studios. It was originally released in 2011 for iOS devices on App Store but it has been ported to many systems including Facebook, Android, Flash, PlayStation, Blackberry, and Windows Phone.

Note

Jetpack Joyride game was titled Machine Gun Jetpack during development.

The reason to create a Jetpack Joyride type game for this book is to teach the developers the perspective and methods of how 2D games are created in Unity from scratch. As Jetpack Joyride game includes all the basic functionalities which are implemented almost in all types of 2D games such as side scrolling, parallax scrolling, sprite sheets, jumping, random obstacle generation, enemy generation, enemy Artificial Intelligence, particle systems, and animations.

Perky Penguin gameplay

The game features a penguin that is on ice in very cool (pun intended) and that's why she is called penguin. In order to navigate through an ice field in the time of global warming, she gets a hold of a jetpack, which is tied on her back. The game uses a simple, one-touch system to control the penguin; when the player presses anywhere on the touchscreen, the penguin's jetpack is fired and penguin rises above the ground making a feel like she is flying for a moment. When the player lets go, the jetpack turns off and penguin falls. The game is continuously running in side view, so player is not required to control the speed of penguin. The player is only able to control the vertical movement of penguin by turning the jetpack on and off.

The objective of the game is to travel as far as possible, collect fish coins, and avoid obstacles such as zappers, missiles, and high-intensity laser beams.

In the next section, we will start the development of the Perky Penguin game. We will learn how to add the player, which in our case is a penguin with jetpack tied to her back, to the game.

 

Adding the penguin


In this section, we will learn how to add our penguin player to the game and how we can make her alive by writing scripts, applying physics, and adding colliders in it.

 

 

Importing the penguin Sprite

Before we do anything, we need a player Sprite or image. For our Perky Penguin game, we have designed a penguin sprite. The following figure shows the penguin that is included as the player sprite of the game:

Figure 1.35 Penguin Sprite

To import an image in to Unity, right-click on the Graphics folder in the Project Browser panel and click on Import New Asset..., as shown in the following screenshot:

Figure 1.36 Import New Asset in Unity

These assets can be anything that is supported by Unity, such as images, audio files, 3D models, textures, materials, and scripts.

Note

Assets can also be imported by dragging image files from Explorer to Unity's project browser panel.

Unity shows all the images with nice previews. It must be noted here that if Unity is in 2D mode, then unity will show images as sprites and if mode is set to 3D mode it shows the images as textures. Figure 1.36 shows both scenarios. The following screenshot shows the image imported as sprite and the screenshot besides it shows image imported as texture:

Figure 1.37 Images as Sprites (left) and Images as Textures (right)

If the penguin image is imported as texture, then there is nothing to worry about. Select the image from Project Browser panel, and in the inspector change the Texture Type to Sprite and click Apply. It is shown in the following figure:

Figure 1.38 Change Texture Type of Image in Inspector Panel

Creating penguin game object

After the assets are imported, which in our case is a single penguin image, we have to create a game object of player. Usually game objects are created by right-clicking in Hierarchy and selecting Create Empty as shows in the following figure:

Figure 1.39 Creating Empty Game Object

But, in order to create sprites as game objects, simply drag sprites from the Project Browser panel to Hierarchy or Scene View panels and a game object will be created with the name of image file which is penguin_fly.png here. This is shown in the following figure:

Figure 1.40 Creating Sprite Game Object

Now it's time to configure the penguin_fly game object of Hierarchy to get used in the game. Now select the penguin_fly object and make following changes in the Inspector panel.

  1. Change the game object's name to penguin.
  2. Set the position values to (0, 0, 0).
  1. To add a collider in the penguin, click Add Component in the inspector and select Circle Collider 2D from Physics2D menu as shown in the following figure. More about Colliders can be read here https://docs.unity3d.com/ScriptReference/Collider.html:

Figure 1.41 Adding Circle Collider 2D

  1. Set the value of Radius of Circle Collider 2D to 0.6.
  2. To make the penguin behave as a physical object, we have to add Rigid Body component. To add it, click Add Component in the Inspector panel and select Rigid Body 2D from Physics2D as shown in the following figure:

Figure 1.42 Adding Rigid Body 2D

  1. Set Fixed Angle checkbox state as checked on to avoid penguin to be rotated while falling or jumping due to physics dynamics.

The following figure below shows all the steps performed on the penguin game object:

Figure 1.43 Penguin Inspector Settings

Starting from position, we have set the position to zero just for testing purposes. We will change it later when we put penguin at its initial position. The Sprite Renderer component is already added in the penguin game object because penguin game object was created from sprite by dragging it from Project Browser panel. The Sprite Renderer allows any game object to show an image on the screen from any sprite. In order to make any game object to react to physics collisions and get collided with each other, game object requires collider component in it. We have added Circle Collider 2D on the penguin object. You can choose any type of collider from the list. But it is recommended to choose the collider which is very light and fills the whole colliding area. The following figure shows the penguin with different colliders applied to it:

Figure 1.44 Penguins with Different Colliders

Using complex colliders like Polygon Collider 2D makes it harder to detect collision for the physics engine to detect collision, which in turn, creates a performance penalty. Finally, in order to apply gravity on the penguin, we have added Rigid Body 2D component. Rigid Body 2D allows any game objects to behave to the gravity, friction, physics kinematics and so on. We have check Fixed Angle to on state of the Rigid Body 2D. If this is set to off, then penguin will also rotate due to wind, friction, gravity, or any other force applied on it. So in order to avoid her to rotate while jumping, we have set Fixed Angle as checked.

Note

There are Physics components and Physics2D components. These both are very different in functionality and are used for very different purposes. You must be very careful when apply physics components on the game objects.

When you run the project, you will notice that penguin will fall down on the screen. It is because of the gravity is pulling penguin downwards and it goes off the screen. The Gravity Scale value, which is 1 by default, decides the gravity of the penguin. If we remove or disable Rigid Body 2D component, then penguin will never move. So, it must be noted that without rigid body no force and collision will be applied on the game object.

Adding script behavior on penguin object

After setting physics components and position on penguin object, it's time to define some logic behavior of the penguin. The game's requirements are to let penguin fly through its jetpack when screen is touched by player and penguin will fall when touch is stopped. These kinds of logic are defined in Unity through scripts. Unity supports 2 kinds of scripts; C# and JavaScript. You can use any of these scripts. Even you can also use few files in C# and few other files in JavaScript in the same project. Throughout this book, we will do all the scripting through C#.

  1. We will start by creating a C# script file in Scripts folder in Assets by right-clicking on Scripts folder and choose C# Script from Create menu as shown in the following figure:

Figure 1.45 Adding a C# Script

  1. Let's call this script as PenguinController.cs and when you open it, the Unity's default Code Editor Visual Studio will start and open the newly created script file it as shown in the following figure.

Figure 1.46 A C# Script File in MonoDevelop

  1. You might notice some code already written in this file. We will discuss about it in a while. Now a script has been created, but this script is not linked or connected to our penguin object or even the game. In order to apply it on the penguin object, select penguin game object, click on Add Component in the Inspector panel, and choose PenguinController.cs from Scripts menu as shown in the following figure:

Figure 1.47 Adding C# Script on Penguin GameObject

Note

You can also apply script on the game object by directly dragging script file on the game object in hierarchy view.

Now, as the script is applied on the penguin game object, let's write some logic and code to make the penguin fly. Open PenguinController.cs file from project browser panel by double-clicking it in MonoDevelop. The code which is already written looks like the following screenshot:

  1. The PenguinController class is inherited from MonoBehaviour class. Any script to be applied on any game object placed in the scene should be a MonoBehaviour class and this is done by inheriting the class from it. MonoBehaviour class provides some basic functionality for game objects such as its life cycle like when object is created, when it is active, when it is destroyed etc. Also it provides some functionality like interactions such as mouse down or mouse up etc. For now, we have only two methods Start() and Update(). The Start() method is called when the game object becomes first time active on the scene at runtime and Update() method is called on each frame if the game object is enabled or active.

Note

You can also use Visual Studio 2012 with Unity for C# scripts by installing Visual Studio Unity Tools and importing UnityVS packaging in the project.

  1. Now, let's start our logic for penguin. We will start from creating a variable jetpackForce in the class like this:
        public float jetpackForce = 75.0f;

 

  1. We have set its initial float value to 75 and f letter is to make it float literal. There is an interesting thing about Unity that all the public fields in any class will be shown in game object's inspector component and can be altered or modified directly from the editor without opening the code file. The following shows the jetpackForce variable's field in the inspector panel:

Figure 1.48 The jetpackForce Field in the Inspector Panel

  1. Next is to use this jetpackForce's value as the force to apply on penguin when touch is pressed. In order to detect touches, we have to use Input.GetButton() method. But this method is better used in either Update() or FixedUpdate() methods of MonoBehaviour class. The FixedUpdate() method is called every fixed frame instead of every frame. Meaning that in FixedUpdate() if the FPS of the game is 60 then the FixedUpdate function will be called 60 times in a second. Irrespective if there are any changes to the scene. In comparison the Regular Update () function gets doesn't stick to the 60 fps rule and will update when there is a change in the scene. This should be used when dealing with RigidBody. As our penguin is a RigidBody2D, so it's better to use FixedUpdate() method than Update(). The PenguinController.cs script doesn't contain FixedUpdate() method, so let's add the following code in the class now:
        void FixedUpdate()
        {
            bool jetpackkActive = Input.GetButton ("Fire1);
            if (jetpackActive = true) {
                this.GetComponent<Rigidbody>().AddForce(new Vector2(0, 
                jetpackForce));
            }
        }

 

  1. There is nothing difficult here. We are polling for the input of Fire1 button which is a left-click in case of any PC, Linux, or MAC build and it changes to touch on Android, iPhone or other touch device. If the screen is touched, then GetButton() will return true value, which in turn lets script add force by calling AddForce() method of the RigidBody2D component and passing the jetpackForce value in the y-direction.

Following is the whole PenguinController.cs file's code: 

  1. Now, when you run the game the penguin will start falling. On clicking on screen, the penguin will rise up a little and will start falling again. The more frequently clicks are performed, the higher penguin will go up and it will easily be out of the screen within 2 or 3 clicks. Also it is falling very fast. In order to adjust its speed, either we decrease Gravity Scale from RigidBody2D of the penguin object as shown in the following figure on left side or we decrease the Gravity in the Physics2D settings shown in the figure on right side.

Figure 1.49 Gravity Scale of Penguin (left) and Gravity of Physics2D (right)

We will change the Gravity value of Physics2D settings to -15. You can open Physics2D settings from Edit - Project Settings - Physics2D menu.

Now run the game, and you will notice the penguin will fall slower than before. On clicking many times, you might notice that penguin gets out of the screen. This kind of behavior in the games should be avoided. So, in order to limit the penguin within the screen bounds, we will add floor and ceiling in the game. Let's see how it's done in the next section.

Limiting the penguin between screen bounds

Adding floor and ceiling is quite simpler job. We will create an empty object first. It should be noted that we are not importing any images or sprite assets in the scene, because we only need boundaries not the visuals of those about how these will look. Here is how we create our floor object.

  • Create empty game object by choosing GameObject - Create Empty menu.
  • Select newly created empty game object in the Hierarchy panel.
  • Rename it to floor.
  • Set its Position to (0, -3.25, 0).
  • Set its Scale to (14.4, 1, 1).
  • Add Box Collider 2D component by clicking on Add Component, and selecting Physics2D - Box Collider 2D option.

Now you should be seeing a green rectangle on bottom of screen. This is the box collider of the floor and when you run the game, the penguin will never fall off the screen and it will stop when collided with the floor.

Note

We haven't added Rigid Body 2D on floor object because we don't want to apply gravity on the floor object due to its static nature.

Similarly, now add ceiling game object with the name ceiling and its position of (0, 3.25, 0) and its scale of (14.4, 1, 1). Apply Rigid Body 2D component on the ceiling object, and now run the project. You will observe that penguin now never leaves the screen and it is limited between the upper and lower parts of the screen.

 

Summary


In this chapter, we learnt about what is Android and about its different versions. We also learnt about different game engines such as Unity3D, Unreal Engine, Game Maker Studio, or Adobe Flash used to create games for Android devices. We also learnt about important features of Unity along with its basics of its development environment. After learning basics of unity game development, we learnt about configuration of any empty game projects for 2D games. Then we got introduced to the Perky Penguin game which started getting developed in this chapter. A penguin was added and its basic flying and falling functionality was created in this chapter then.

In the next chapter, we will finish the Perky Penguin game and see how particle systems, animations, enemies, and so on, are all developed in Unity.

About the Authors
  • Wajahat Karim

    Wajahat Karim is a seasoned mobile app and game developer with extensive experience in diversified technologies, as well as more than 7 years of software development experience. Wajahat received his information and communication systems engineering degree from the NUST School of Electrical Engineering and Computer Sciences (SEECS), Islamabad, Pakistan. He has been working on games since he was 14 years old and is skilled in many platforms, including Android SDK, AndEngine, Adobe Flash, Adobe AIR, Game Maker, and Unity3D. He is skilled, not only in programming and coding, but also in computer graphic designing tools such as Adobe Photoshop, Adobe Illustrator, Adobe Flash, and Autodesk Maya. Recently, he also worked with the government of Oman in Muscat, to create a real-time election monitoring app for Android and iOS for their Shura Elections, 2015. He has run multiple startups from time to time and has also worked in a virtual reality and augmented reality startup. Currently, besides being a full-time development manager at a multinational company, he is working with a startup that allows Android developers to boost their app growth and reward their users through in-app perks. Wajahat has deep passion in game development, entrepreneurship, and writing. He has previously coauthored the book Learning Android Intents by Packt Publishing. You can reach Wajahat on his personal website.

    Browse publications by this author
  • Siddharth Shekar

    Siddharth Shekar is a game developer and teacher with over 6 years' industry experience and 12 years' experience in C++ and other programming languages. He is adept at graphics libraries such as OpenGL and Vulkan, and game engines such as Unity and Unreal. He has published games on the iOS and Android app stores. He has also authored books including Swift Game Development, Mastering Android Game Development with Unity, and Learning iOS 8 Game Development Using Swift, all published by Packt Publishing. He currently lives in Auckland, New Zealand, and is a lecturer in the games department at Media Design School. He teaches advanced computer graphics programming, PlayStation 4 native game development, and mentors final year production students.

    Browse publications by this author
Latest Reviews (3 reviews total)
The Packt website is well set up and easy to navigate.
Libro è risultato utile. Ottimo riferimento.
Das Buch ist in einer englisch-ähnliche Sprache geschrieben, aber nicht in englisch. Falls ich es konnte, würde ich es zurückgeben
Mastering Android Game Development with Unity
Unlock this book and the full library FREE for 7 days
Start now