Unity Android Game Development by Example Beginner's Guide - Thomas James Finnegan - E-Book

Unity Android Game Development by Example Beginner's Guide E-Book

Thomas James Finnegan

0,0
34,79 €

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

Mehr erfahren.
Beschreibung

Powerful and continuing to grow, the mobile market has never been bigger and more demanding of great games. Android continues to prove itself as a strong contender in this challenging market. With Unity 3D, great games can be made for Android quickly and easily. With its great deployment system, the Android platform is now only one click away.

Unity Android Game Development by Example Beginner's Guide dives straight into making real, fully-functional games, with hands-on examples and step-by-step instructions to give you a firm grounding in Unity 3D and Android. Everything necessary for creating a complete gaming experience is covered and detailed throughout the course of this book.

Using clear and practical examples that progressively build upon each other, this book guides you through the process of creating games in Unity for Android.

Start by learning about all the great features that Unity and Android have to offer. Next, create a Tic-Tac-Toe game while learning all about interfaces. After that, learn about meshes, materials, and animations with the creation of a tank battle game. You will then learn how to expand your game's environment with the addition of shadows and a skybox. Adding on this, you will also learn how to expand the tank battle by creating enemies and using path finding to chase the player. Next, explore touch and tilt controls with the creation of a space fighter game. Then, learn about physics while recreating the most popular mobile game on the market. You will then expand the space fighter game with the addition of all the special effects that make a game great. Finally, complete your experience by learning the optimization techniques required to keep your games running smoothly.

While Unity is available for both Mac and Windows, the book is presented working from a Windows environment. Programming in Unity is possible in C#, JavaScript, and Boo. This book will be working in C# and the final projects will be provided in C# and JavaScript.

From nothing to a fully-featured mobile game, Unity Android Game Development by Example Beginner's Guide takes you through everything it takes to create your next game for the Android platform.

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

EPUB
MOBI

Seitenzahl: 486

Veröffentlichungsjahr: 2013

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

Unity Android Game Development by Example Beginner's Guide
Credits
About the Author
About the Reviewers
www.PacktPub.com
Support files, eBooks, discount offers and more
Why Subscribe?
Free Access for Packt account holders
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. Saying Hello to Unity and Android
Understanding what makes Unity great
Understanding what makes Android great
Understanding how Unity and Android work together
Differences between Pro and Basic
License comparison overview
Setting up the development environment
Time for action – installing the JDK
What just happened?
Time for action – installing the Android SDK
What just happened?
Time for action – installing Unity 3D
What just happened?
Optional code editor
Connecting to a device
Time for action – simple device connection
What just happened?
Time for action – connecting trickier devices
What just happened?
Unity Remote
Building a simple application
Time for action – Hello World
What just happened?
Have a go hero – working ahead
Summary
2. Looking Good – Graphical Interface
Creating a Tic-tac-toe game
Time for action – creating Tic-tac-toe
What just happened?
Finishing the game
Time for action – finish creating the game
What just happened?
GUI Skins and GUI Styles
A prettier form of Tic-tac-toe
Time for action – styling the game
What just happened?
Have a go hero – backgrounds
Dynamic positioning
Time for action – the dynamic GUI
What just happened?
Have a go hero – scaling menus
A better way to build to device
Time for action – build and run
What just happened?
Have a go hero – single player mode
Summary
3. The Backbone of Any Game – Meshes, Materials, and Animations
Setting up
Time for action – the setup
What just happened?
Importing the meshes
Time for action – importing the tank
What just happened?
Tank import settings
Setting up the tank
Time for action – creating the tank
What just happened?
Time for action – keeping score
What just happened?
Time for action – controlling the chassis
What just happened?
Time for action – controlling the turret
What just happened?
Time for action – putting the pieces together
What just happened?
Have a go hero – cannon alignment
Creating the materials
Time for action – creating the city
What just happened?
Have a go hero – decorating the city
Time for action – moving treads
What just happened?
Have a go hero – turning with the treads
Animations
The target's animations
Time for action – setting up target's animations
What just happened?
State machines
Time for action – creating the target state machine
What just happened?
Time for action – scripting the target
What just happened?
Creating the prefab
Time for action – creating the target
What just happened?
Have a go hero – more targets
Ray tracing to shoot
Time for action – simple shooting
What just happened?
Have a go hero – better GUI
Summary
4. Setting the Stage – Camera Effects and Lighting
The camera effects
Skyboxes and distance fog
Time for action – adding a skybox and distance fog
What just happened?
Target indicator
Time for action – creating the pointer
What just happened?
Time for action – controlling the indicator
What just happened?
Time for action – working with a second camera
What just happened?
Have a go hero – adjusting the position
Turbo boost
Time for action – using the boost effect
What just happened?
Have a go hero – styling and control
Lights
Time for action – adding more lights
What just happened?
Lightmaps
Time for action – creating a lightmap
What just happened?
Have a go hero – reason and speed
Cookies
Time for action – applying headlights
What just happened?
Have a go hero – adding a switch
Blob shadow
Time for action – a tank with a shadow
What just happened?
Have a go hero – making it square
Summary
5. Getting Around – Pathfinding and AI
Understanding AI and pathfinding
The NavMesh
Time for action – creating the NavMesh
What just happened?
Have a go hero – creating extra obstacles
The NavMeshAgent component
Time for action – creating the enemy
What just happened?
The chase
Time for action – the player is over here
What just happened?
Time for action – chasing the player
What just happened?
Have a go hero – adding shadow
Being attacked
Time for action – getting ready to fire
What just happened?
Have a go hero – player feedback
Attacking the enemy
Time for action – giving it a weakness
What just happened?
Have a go hero – coloring the enemy
Spawning
Time for action – creating spawns
What just happened?
Have a go hero – two for one
Pop Quiz – understanding enemies
Summary
6. Specialties of the Mobile Device – Touch and Tilt
Setting up
Time for action – creating the project
What just happened?
Controlling with tilt
Time for action – steering the space ship
What just happened?
Making things move in space
Time for action – flying asteroids
What just happened?
Adding space collisions
Time for action – adding collisions
What just happened?
Have a go hero – adding points
Creating the enemy
Time for action – adding an enemy ship
What just happened?
Have a go hero – skybox and fog
Controlling with touch
Time for action – touch to shoot
What just happened?
Have a go hero – healthy ships
Spawning in space
Time for action – creating a space spawn
What just happened?
Have a go hero – more to spawn and shoot
Pop Quiz – understanding Android components
Summary
7. Throwing Your Weight Around – Physics and a 2D Camera
2D games in a 3D world
Time for action – preparing the world
What just happened?
Physics
Building blocks
Time for action – creating planks
What just happened?
Have a go hero – creating a stone block
Physics materials
Time for action – sliding and bouncing
What just happened?
Characters
The enemy
Time for action – creating the pigs
What just happened?
The ally
Time for action – creating the red bird
What just happened?
Controls
Attacking
Time for action – creating the slingshot
What just happened?
Watching
Time for action – controlling the camera
What just happened?
Have a go hero – more levels
A better background
Time for action – creating the parallax background
What just happened?
Have a go hero – dark of the night
The flock variety
The yellow bird
Time for action – creating the yellow bird
What just happened?
The blue bird
Time for action – creating the blue bird
What just happened?
Have a go hero – creating a rainbow bird
The black bird
Time for action – creating the black bird
What just happened?
Have a go hero – explosive blocks
Level selection
Time for action – creating the level selection
What just happened?
Have a go hero – adding some style
Summary
8. Special Effects – Sound and Particles
Understanding audio
Import settings
Audio Listener
Audio Source
Adding background music
Time for action – adding background music
What just happened?
Have a go hero – setting some mood
Creating an alarm system
Time for action – warning the player
What just happened?
Have a go hero – differentiation
Understanding particle systems
Particle system settings
Creating engine trails
Time for action – adding engine trails
What just happened?
Have a go hero – more trails
Putting it together
Explosions
Time for action – adding explosions
What just happened?
Have a go hero – more types of explosions
Creating laser blasts
Time for action – adding laser blasts
What just happened?
Have a go hero – more types of lasers
Summary
9. Optimization
Minimizing the application footprint
Editor log
Asset compression
Models
Model tab
Rig tab
Animations tab
Textures
Audio
Player settings
Rendering
Optimization
Tracking performance
Editor statistics
The Profiler
Tracking script performance
Time for action – tracking scripts
What just happened?
Minimizing lag
Occlusion
Time for action – occluding tanks
What just happened?
Points to remember
Summary
A. Pop Quiz Answers
Chapter 5, Getting Around – Pathfinding and AI
Pop quiz – understanding enemies
Chapter 6, Specialties of the Mobile Device – Touch and Tilt
Pop quiz – understanding Android components
Index

Unity Android Game Development by Example Beginner's Guide

Unity Android Game Development by Example Beginner's Guide

Copyright © 2013 Packt Publishing

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

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

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

First published: December 2013

Production Reference: 1131213

Published by Packt Publishing Ltd.

Livery Place

35 Livery Street

Birmingham B3 2PB, UK.

ISBN 978-1-84969-201-4

www.packtpub.com

Cover Image by Thomas Finnegan (<[email protected]>)

Credits

Author

Thomas Finnegan

Reviewers

Mootez Billeh Chaabani

Valera Kogut

Marc Schaerer

Aris Tsevrenis

Acquisition Editor

Owen Roberts

Commissioning Editor

Llewellyn Rozario

Lead Technical Editor

Ritika Dewani

Technical Editors

Arwa Manasawala

Ankita Thakur

Project Coordinator

Anugya Khurana

Copy Editors

Roshni Banerjee

Deepa Nambiar

Karuna Narayanan

Laxmi Subramanian

Proofreader

Stephen Copestake

Indexer

Rekha Nair

Graphics

Disha Haria

Production Coordinator

Manu Joseph

Cover Work

Manu Joseph

About the Author

Thomas Finnegan completed his graduation from Brown College in 2010. Since then, he has worked on everything from mobile platforms to web development, and even experimental devices. He now works as a freelance game developer. Past clients include Carmichael Lynch, Coleco, and Subaru. His most recent project is Battle Box 3D, a virtual table top. Currently he is teaching game development at the Minneapolis Media Institute in Minnesota.

I would like to thank my fiancée for kicking me into gear whenever I was distracted. Also, I would like to thank my parents for always supporting me. Without my friends and family, life would be dismal.

About the Reviewers

Mootez Billeh Chaabani is a software engineer. Currently he is working as a software engineer (Research and Development) in a French company named SpacEyes. He recently completed his graduation. He studied graphical programming and virtual and augmented reality. He also published two apps: Quizz game in the Windows Marketplace and an Android app in the local appshop, and now he is working on Android/C++ projects based on 3D in SpacEyes. Before this, he was an intern at Microsoft Tunisia in 2011. He also worked as an Android developer in Orange Tunisia in 2012. He also worked on the book Android NDk Game Development Cookbook.

I would like to thank my family, my soulmate, and all of my friends including Bardo Boys (my neighborhood friends).

Valera Kogut is a passionate software developer with different areas of expertise. Before diving into the game industry five years ago, Valera was creating for Web with PHP and Yii frameworks. Having a mathematical background, he finally realized gamedev was his mission. Reusable designs, optimized algorithms, clean code, and elaborated workflows—these things make him happy. He is a co-founder and principal architect at applicat.io, software development agency offering a wide range of services (http://applicat.io). However, architectural and management tasks can't stop Valera from digging deeply into code.

Currently, Valera executes one contract as Unity3D C# developer for Kaufcom GmbH, a known games and apps producer from Switzerland http://www.kauf.com (Android games https://play.google.com/store/search?q=kaufcom).

First of all, thanks to the author and team from Packt Publishing for creating this book, and thereby helping the Unity community grow and mature. Special thanks go to my family for the love, education, and freedom they gave me! I would also like to thank my best friends and associates at applicat.io, Paul Kofmann, Alexander Kofmann, and Vitaly Shapovalov; we are the Team! Thanks to the Kaufcom Company! And of course, no progress of mine could be achieved without the support and love of my wife, Irina.

Marc Schaerer is an interactive media software engineer who is creating cutting edge interactive media experiences for training, education, and entertainment purposes on mobile, desktop, and web platforms for customers through his company Gayasoft (http://www.gayasoft.net) located in Switzerland.

His technology of choice is Unity, which he has been using since its early days in 2007.

He has a strong background in 3D graphics, network technology, software engineering, and the interactive media field. Originally, he started programming at the age of 11 and built upon it later while studying Computer Science and Computational Science and Engineering at Swiss Federal Institute of Technology, Zurich, thereby growing into it. This knowledge found, among other projects, usage in Popper (http://www.popper.org), an interactive 3D behavioral research platform by Harvard developed by Gayasoft and powered by Unity, Mathlab, and the ExitGames Photon.

With the rise of serious games, he focused on researching options and technologies for the next generation of interactive and immersive experiences, applying state of the art AR and VR technologies (Vuforia, Metaio, and Oculus Rift) and new innovative input technologies (Razer Hydra, STEM, Leap Motion, and Emotive Insight). He predicts that this will become the base of future experiences in many fields of our daily life.

Aris Tsevrenis is a game developer and director at Terahard Ltd, a game development studio dedicated to creating addictive games that will be remembered for their quality in every aspect. The company's motto, "Terabytes of Quality for Hardcore Gaming", explains a few things about Aris' ambitions. Aris was introduced to games from a very early age in the 90s. Showing great skill, and evolving from chess to modern computer and console games, Aris became famous among the people who knew his numerous feats in the gaming world. He received his BSc in Computer Science with a Computer Vision and Computer Graphics degree in 2009 from Cardiff University in Wales, followed by an MSc in Computer Games and Entertainment degree from Goldsmith's University in London. He entered the games development world and worked in a few different games companies until he set up Terahard Ltd. He currently lives in London, where his games studio is located, and can be contacted at <[email protected]>.

www.PacktPub.com

Support files, eBooks, discount offers and more

You might want to visit www.PacktPub.com for support files and downloads related to your book.

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.

http://PacktLib.PacktPub.com

Do you need instant solutions to your IT questions? PacktLib is Packt's online digital book library. Here, you can access, read and search across Packt's entire library of books.

Why Subscribe?

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

Free Access for Packt account holders

If you have an account with Packt at www.PacktPub.com, you can use this to access PacktLib today and view nine entirely free books. Simply use your login credentials for immediate access.

Preface

In this book, we explore the ever-expanding world of mobile game development. Using Unity 3D and the Android SDK, we will learn how to create every aspect of a mobile game. Every chapter explores another piece of the development puzzle. Exploring the special features of development with mobile platforms, every game in the book is designed to increase your understanding of these features. We also finish the book with a total of four complete games and all of the tools we need to create many more.

The first game that we make is Tic-tac-toe. This game functions just as the classic paper version. Two players take turns filling a grid with their symbols; the first to make a line of three wins. It is the perfect game for us to explore the graphical interface options that we have in Unity. By learning how to add buttons, text, and pictures to the screen here, we have all of the understanding and tools needed to add any interface that we might want to any game.

The next game that we create is the Tank Battle game. The player takes control of a tank to drive around a small city and shoot targets and enemies. This game spans three chapters, allowing us to explore many key points of creating games for the Android platform. We start by creating a city and making the player's tank move around, using controls that we learned about when making the Tic-tac-toe game. We also create and animate the targets that the player will shoot at. In the second part of this game, we add some lighting and special camera effects. By the end of the chapter, the environment looks great. In the third part of the game's creation, we create some enemies. Using the power of Unity, these enemies chase the player throughout the city, and attack when they are close.

The third game to be completed is a simple clone of a popular mobile game. Using the power of Unity's physics system, we are able to create structures and throw birds at them. Knock down the structures to gain points, and destroy the target pigs to win the level. We also take the time to explore some of the specific features of a 2D game, such as a parallax scrolling background, and how they can be achieved in Unity. We complete the chapter and the game with the creation of a level selection menu.

Finally, we create the Space Fighter game. This game involves using the special inputs of a mobile device to control the player's ship. As the player's device is tilted, they will be able to steer the ship. When they touch the screen, they can shoot at the enemy ships and asteroids. The second part of this game involves including the special effects that complete the look of every game. We create explosions when ships are destroyed, and engine trails for the ships. We also add the sound effects for shooting and exploding.

The book wraps up with a look at optimization. We explore all of the great features of Unity, and even create a few of our own to make our game run as best as it can. We also take a little bit of time to understand some things that we can do to minimize the file size of our assets while maximizing their look and effect in the game. At this point, our journey ends, but we have four great games that are just about ready to go to market.

What this book covers

Chapter 1, Saying Hello to Unity and Android, explores the feature lists of the Android platform and the Unity 3D game engine, covering why they are great choices for development. We will also cover setting up the development environment, and create a simple Hello World application for your device and emulators.

Chapter 2, Looking Good ­– Graphical Interface, takes a detailed look at the graphical user interface. By creating a Tic-tac-toe game, we learn about the user interface while making it pleasing to look at.

Chapter 3, The Backbone of Any Game ­– Meshes, Materials, and Animations, explores meshes, materials, and animations. Through the creation of a Tank Battle game, we cover the core of what players will see when playing.

Chapter 4, Setting the Stage ­– Camera Effects and Lighting, explains about the camera effects and lighting. With the addition of shadows, lightmaps, distance fog, and a skybox, our Tank Battle environment becomes more dynamic. Utilizing special camera effects, we create extra feedback for the player.

Chapter 5, Getting Around ­– Pathfinding and AI, shows the creation of mobile enemies in our Tank Battle game. We explore pathfinding and AI to give players a target more meaningful than a stationary dummy.

Chapter 6, Specialties of the Mobile Device ­– Touch and Tilt, covers the features that make the modern mobile device special. We create a Space Fighter game to understand the touch interface and tilt controls.

Chapter 7, Throwing Your Weight Around ­– Physics and a 2D Camera, shows the creation of a clone of Angry Birds after taking a short break from the Space Fighter game. Physics and a 2D camera effect are explored here.

Chapter 8, Special Effects ­– Sound and Particles, returns to the Space Fighter game to add special effects. The inclusion of sound effects and particles allows us to create a more complete game experience.

Chapter 9, Optimization, covers optimization in Unity 3D. We cover the benefits and costs of making our Tank Battle and Space Fighter games as efficient as possible.

What you need for this book

Throughout this book, we will be working with both the Unity 3D game engine and Android. As you can see in the previous section, we will cover both the acquisition and installation of Unity and the Android SDK in Chapter 1, Saying Hello to Unity and Android. To get the most of this book, you will need access to an Android-powered device; either a phone or tablet will work well. For simplicity's sake, we will assume that you are working on a Windows-powered computer. Also, the code throughout the book is written in C#, though JavaScript versions of each chapter project are available for reference. To fully utilize the models provided for the chapter projects, you will need Blender, a free modeling program available at http://www.blender.org. To reach all of the challenges, you will need to make use of either Blender or another modeling program that you are comfortable with, for example, a photo-editing program; Photoshop is a common choice, and a source for the creation or acquisition of audio files. All of the audio files provided by this book were found at http://www.freesound.org.

Who this book is for

This book will be optimal for readers who are new to game development and mobile development with Unity. Readers who learn best with real-world examples rather than dry documentation will find every chapter useful. Even if you have little or no programming skills, this book will make a great place to jump in and learn some concepts and standards for programming.

Conventions

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

Code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles are shown as follows: "If during the build process, Unity complains about where the Android SDK is, select the android-sdk folder inside the location where it was installed."

A block of code is set as follows:

public void OnGUI() { GUILayout.Label("Hello World"); }

Any command-line input or output is written as follows:

adb kill-serveradb start-serveradb devices

New terms and important words are shown in bold. Words that you see on the screen, in menus or dialog boxes for example, appear in the text like this: "Follow that up by clicking on the Download the SDK Tools for Windows button".

Note

Warnings or important notes appear in a box like this.

Tip

Tips and tricks appear like this.

Reader feedback

Feedback from our readers is always welcome. Let us know what you think about this book—what you liked or may have disliked. Reader feedback is important for us to develop titles that you really get the most out of.

To send us general feedback, simply send an e-mail to <[email protected]>, and mention the book 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 on 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 all Packt books that you have purchased 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.

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 understand the changes in the output better. You can download this file from: http://www.packtpub.com/sites/default/files/downloads/2014OT_Images.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 would 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 erratasubmissionform link, and entering the details of your errata. Once your errata are verified, your submission will be accepted, and the errata will be uploaded on our website or added to any list of existing errata under the Errata section of that title. Any existing errata can be viewed by selecting your title from http://www.packtpub.com/support.

Piracy

Piracy of copyright 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

You can contact us at <[email protected]> if you are having a problem with any aspect of the book, and we will do our best to address it.

Chapter 1. Saying Hello to Unity and Android

Welcome to the wonderful world of mobile game development. Whether you are still looking for the right development kit or have already chosen one, this chapter will be most important. In this chapter we explore the various features that come with choosing Unity as your development environment and Android as the target platform. Through comparison with major competitors, it is discovered why Unity and Android stand on the top of the pile. Following that, we examine how Unity and Android work together. Finally, the development environment is set up and we create a simple Hello World application to test that everything is set up correctly. For the purposes of this book, it is assumed you are working in a Windows-based environment.

In this chapter, we will cover the following topics:

Major Unity featuresMajor Android featuresUnity licensing optionsInstalling the JDKInstalling the Android SDKInstalling Unity 3DInstalling Unity Remote

Understanding what makes Unity great

Perhaps the greatest feature of Unity is how open-ended it is. Nearly all game engines currently on the market are limited in what one can build. It makes perfect sense but it can limit the capabilities of a team. The average game engine has been highly optimized for creating a specific game type. This is great if all you plan on making is the same game again and again. When one is struck with inspiration for the next great hit, only to find that the game engine can't handle it and everyone has to retrain in a new engine or double the development time to make it capable, it can be quite frustrating. Unity does not suffer this problem. The developers of Unity have worked very hard to optimize every aspect of the engine, without limiting what types of games can be made. Everything ranging from simple 2D platformers to massive online role-playing games is possible in Unity. A development team that just finished an ultra-realistic first-person shooter can turn right around and make 2D fighting games without having to learn an entirely new system.

Being so open ended does, however, bring a drawback. There are no default tools optimized for building that perfect game. To combat this, Unity grants the ability to create any tool one can imagine, using the same scripting that creates the game. On top of that, there is a strong community of users that have supplied a wide selection of tools and pieces, both free and paid, to be quickly plugged in and used. This results in a large selection of available content, ready to jump-start you on your way to the next great game.

When many prospective users look at Unity, they think that because it is so cheap, it is not as good as an expensive AAA game engine. This is simply not true. Throwing more money at the game engine is not going to make a game any better. Unity supports all of the fancy shaders, normal maps, and particle effects you could want. The best part is, nearly all of the fancy features you could want are included in the free version of Unity and 90 percent of the time beyond that, one does not need to even use the Pro only features.

One of the greatest concerns when selecting a game engine, especially for the mobile market, is how much girth it will add to the final build size. Most are quite hefty. With Unity's code stripping, it becomes quite small. Code stripping is the process by which Unity removes every extra little bit of code from the compiled libraries. A blank project, compiled for Android, that utilizes full code stripping ends up being around 7 megabytes.

Perhaps one of the coolest features of Unity is the multi-platform compatibility. With a single project one can build for several different platforms. This includes the ability to simultaneously target mobile, PC, and consoles. This allows one to focus on real issues, such as handling inputs, resolution, and performance.

In the past, if a company desired to deploy their product on more than one platform, they had to nearly double the development costs in order to essentially reprogram the game. Every platform did, and still does, run by its own logic and language. Thanks to Unity, game development has never been simpler. We can develop games using simple and fast scripting, letting Unity handle the complex translation to each platform.

There are of course several other options for game engines. Two major ones that come to mind are cocos2d and Unreal Engine. While both are excellent choices, we can always find them to be a little lacking in certain respects.

The engine of Angry Birds, cocos2d, could be a great choice for your next mobile hit. However, as the name suggests, it is pretty much limited to 2D games. A game can look great in it, but if you ever want that third dimension, it can be tricky to add. A second major problem with cocos2d is how bare bones it is. Any tool for building or importing assets needs to be created from scratch, or they need to be found. Unless you have the time and experience, this can seriously slow down development.

Then there is the staple of major game development, Unreal Engine. This game engine has been used successfully by developers for many years, bringing great games to the world; Unreal Tournament and Gears of War not the least among them. These are both, however, console and computer games, which is the fundamental problem with the engine. Unreal is a very large and powerful engine. Only so much optimization can be done for mobile platforms. It has always had the same problem; it adds a lot of girth to a project and its final build. The other major issue with Unreal is its rigidity in being a first-person shooter engine. While it is technically possible to create other types of games in it, such tasks are long and complex. A strong working knowledge of the underlying system is a must before achieving such a feat.

All in all, Unity definitely stands strong among the rest. Perhaps you have already discovered this, and that is why you are reading this book. But these are still great reasons for choosing Unity for game development. Projects can look just as great as AAA titles. Overhead and girth in the final build is small and very important when working on mobile platforms. The system's potential is open enough to allow you to create any type of game you might want, where other engines tend to be limited to a single type of game. And should your needs change at any point in the project's life cycle, it is very easy to add, remove, or change your choice of target platforms.

Understanding what makes Android great

With over 30-million devices in the hands of users, why would you not choose the Android platform for your next mobile hit? Apple may have been the first one out of the gate with their iPhone sensation, but Android is definitely a step ahead when it comes to smartphone technology. One of its best features is its blatant ability to be opened up so you can take a look at how the phone works, both physically and technically. One can swap out the battery and upgrade the micro SD card, should the need arise. Plugging the phone into a computer does not have to be a huge ordeal; it can simply function as removable storage media.

From the point of view of cost of development, the Android market is superior as well. Other mobile app stores require an annual registration fee of about 100 dollars. Some also have a limit on the number of devices that can be registered for development at one time. The Google Play market has a one-time registration fee, and there is no concern about how many or what type of Android devices you are using for development.

One of the drawbacks about some of the other mobile development kits is that you have to pay an annual registration fee before you have access to the SDK. With some, registration and payment are required before you can view their documentation. Android is much more open and accessible. Anybody can download the Android SDK for free. The documentation and forums are completely viewable without having to pay any fee. This means development for Android can start earlier, with device testing being a part of it from the very beginning.

Understanding how Unity and Android work together

Because Unity handles projects and assets in a generic way, there is no need to create multiple projects for multiple target platforms. This means that you could easily start development with the free version of Unity and target personal computers. Then, at a later date, you can switch targets to the Android platform with the click of a button. Perhaps, shortly after your game is launched, it takes the market by storm and there is a great call to bring it to other mobile platforms. With just another click of the button, you can easily target iOS without changing anything in your project.

Most systems require a long and complex set of steps to get your project running on a device. For the first application in this book, we will be going through that process because it is important to know about it. However, once your device is set up and recognized by the Android SDK, a single-button click will allow Unity to build your application, push it to a device, and start running it. There is nothing that has caused more headaches for some developers than trying to get an application on a device. Unity makes it simple.

With the addition of a free Android application, Unity Remote, it is simple and easy to test mobile inputs without going through the whole build process. While developing, there is nothing more annoying than waiting for 5 minutes for a build every time you need to test a minor tweak, especially in the controls and interface. After the first dozen little tweaks the build time starts to add up. Unity Remote makes it simple and easy to test it all without ever having to hit the Build button.

These are the big three: generic projects, a one-click build process, and Unity Remote. We could, of course, come up with several more great ways in which Unity and Android can work together. But these three are the major time and money savers. You could have the greatest game in the world but, if it takes 10 times as long to build and test, what is the point?

Differences between Pro and Basic

Unity comes with two licensing options, Pro and Basic, which can be found at https://store.unity3d.com. In order to follow the bulk of this book, Unity Basic is all that is required. However, real-time shadows in Chapter 4, Setting the Stage – Camera Effects and Lighting, the whole of Chapter 5, Getting Around – Pathfinding and AI, and some of the optimization features discussed in Chapter 9, Optimization, will require Unity Pro. If you are not quite ready to spend the $3,000 required to purchase a full Unity Pro license with the Android add-on, there are other options. Unity Basic is free and comes with a 30-day free trial of Unity Pro. This trial is full and complete, just as if one has purchased Unity Pro. It is also possible to upgrade your license at a later date. Where Unity Basic comes with mobile options for free, Unity Pro requires the purchase of Pro add-ons for each of the mobile platforms.

License comparison overview

License comparisons can be found at http://unity3d.com/unity/licenses. This section will cover the specific differences between Unity Android Pro and Unity Android Basic. We will explore what the feature is and how useful it is.

NavMeshes, Pathfinding, and crowd Simulation: This feature is Unity's built-in pathfinding system. It allows characters to find their way from point to point around your game. Just bake your navigation data in the editor and let Unity take over at runtime. This feature is great if you don't have the ability or inclination to program a pathfinding system yourself. There is a whole slew of tutorials online about how to program pathfinding and do crowd simulation. It is completely possible to do all of this in Unity Basic; you just need to provide the tools yourself.LOD Support: LOD (Level-of-detail) lets you control how complex a mesh is, based on its distance from the camera. When the camera is close to an object, render a complex mesh with a bunch of detail in it. When the camera is far from that object, render a simple mesh, because all that detail is not going to be seen anyway. Unity Pro provides a built-in system to manage this. However, this is another system that could be created in Unity Basic. Whether using Pro or not, this is an important feature for game efficiency. By rendering less complex meshes at a distance, everything can be rendered faster, leaving more room for awesome gameplay.Audio Filter: Audio filters allow you to add effects to audio clips at runtime. Perhaps you created gravel footstep sounds for your character. Your character is running, and we can hear the footsteps just fine, when suddenly they enter a tunnel and a solar flare hits, causing a time warp and slowing everything down. Audio filters would allow us to warp the gravel footstep sounds to sound like they are coming from within a tunnel and are slowed by a time warp. Of course, you could also just have the audio guy create a new set of tunnel gravel footsteps in the time warp sounds. But this might double the amount of audio in your game and limits how dynamic we can be with it at runtime. We either are or are not playing the time warp footsteps. Audio filters would allow us to control how much time warp is affecting our sounds.Video Playback and Streaming: When dealing with complex or high-definition cut scenes, being able to play a video becomes very important. Including them in a build especially with a mobile target can require a lot of space. This is where the streaming part of this feature comes in. This feature not only lets us play video, it also lets us stream that video from the internet. There is, however, a drawback to this feature. On mobile platforms, the video has to go through the device's built-in, video-playing system. This means the video can only be played full-screen and cannot be used as a texture. Theoretically, though, you could break your video into individual pictures for each frame and flip through them at runtime, but this is not recommended for build size and video quality reasons.Fully Fledged Streaming with Asset Bundles: Asset bundles are a great feature provided by Unity Pro. They allow you to create extra content and stream it to the users, without ever requiring an update to the game. You could add new characters, levels, or just about any other content you can think of. Their only drawback is that you cannot add more code. The functionality cannot change, but the content can. This is one of the best features of Unity Pro.100,000 Dollar Turnover: This one isn't so much a feature as it is a guideline. According to Unity's End User License Agreement, the basic version of Unity cannot be licensed by any group or individual that made $100,000 in the previous fiscal year. This basically means, if you make a bunch of money, you have to buy Unity Pro. Of course, if you are making that much money, you can probably afford it without issue. That is the view of Unity at least, and the reason why it is there.Mecanim: IK Rigs: Unity's new animation system, Mecanim, supports many exciting new features, one of which is IK. If you are unfamiliar with the term, IK allows one to define the target point of an animation and let the system figure out how to get there. Imagine you have a cup sitting on a table and a character that wants to pick it up. You could animate the character to bend over and pick it up, but what if the character is slightly to the side? Or any number of other slight offsets that a player could cause, completely throwing off your animation. It is simply impractical to animate for every possibility. With IK, it hardly matters that the character is slightly off. We just define the goal point for the hand and leave the arm to the IK system. It calculates for us how the arm needs to move in order to get the hand to the cup. Another fun use is making characters look at interesting things as they walk around a room. A guard could track the nearest person, the player character could look at things that they can interact with, or a tentacle monster could lash out at the player without all the complex animation. This will be an exciting one to play with.Mecanim: Sync Layers & Additional Curves
Sync layers, inside Mecanim, allow us to keep multiple sets of animation states in time with each other. Say you have a soldier that you want to animate differently based on how much health he has. When at full health, he walks around briskly. After a little damage, it becomes more of a trudge. If health is below half, a limp is introduced to his walk. And when almost dead, he crawls along the ground. With sync layers, we can create one animation state machine and duplicate it to multiple layers. By changing the animations and syncing the layers, we can easily transition between the different animations while maintaining the state machine.Additional curves are simply the ability to add curves to your animations. This means we can control various values with the animation. For example, in the game world, when a character picks up their feet for a jump, gravity will pull them down almost immediately. By adding an extra curve to that animation, in Unity, we can control how much gravity is affecting the character, allowing them to actually get in the air when jumping. This is a useful feature for controlling such values right alongside the animations, but one could just as easily create a script that holds and controls the curves.
Custom Splash Screen: Though pretty self-explanatory, it is perhaps not immediately evident why this feature is specified, unless you have worked with Unity before. When an application built in Unity initializes on any platform, it displays a splash screen. In Unity Basic this will always be the Unity logo. By purchasing Unity Pro, you can substitute the Unity logo with any image you want.Build Size Stripping: This is an important feature for mobile platforms. Build size stripping removes all of the excess from your final build. Unity does a very good job at only including the assets that you have created that are used in the final build. With the stripping, it also only includes the parts of the engine itself that are used in the game. This is of great use when you absolutely have to get under that limit for downloading from the cell towers. On the other hand, you could create something similar to the asset bundles. Just let the users buy the framework, and download the assets later.Realtime Directional Shadows: Lights and shadows add a lot to the mood of a scene. This feature allows us to go beyond blob shadows and use realistic looking shadows. This is all well and good if you have the processing space for it. Most mobile devices do not. This feature should also never be used for static scenery. Instead, use static lightmaps, which is what they are for. But if you can find a good balance between simple needs and quality, this could be the feature that creates the difference between an alright and an awesome game.HDR, tone mapping: HDR (High Dynamic Range) and tone mapping allow us to create more realistic lighting effects. Standard rendering uses values from zero to one to represent how much of each color in a pixel is on. This does not allow for a full spectrum of lighting options to be explored. HDR lets the system use values beyond this range and process them using tone mapping to create better effects, such as a bright morning room or the bloom from a car window reflecting the sun. The downside of this feature is in the processor. The device can still only handle values between zero and one, so converting them takes time. Additionally, the more complex the effect, the more time it takes to render it. It would be surprising to see this used well on handheld devices, even in a simple game. Maybe the modern tablets could handle it.Light Probes: Light probes are an interesting little feature. When placed in the world, light probes figure out how an object should be lit. Then, as a character walks around, they tell it how to be shaded. The character is, of course, lit by the lights in the scene but there are limits on how many lights can shade an object at once. Light probes do all the complex calculations beforehand, allowing for better shading at runtime. Again, however, there are concerns about the processing power. Too little and you won't get a good effect; too much and there will be no processing left for playing the game.Lightmapping with Global Illumination and area lights: All versions of Unity support lightmaps, allowing for the baking of complex static shadows and lighting effects. With the addition of global illumination and area lights, you can add another touch of realism to your scenes. However, every version of Unity also lets you import your own lightmaps. This means, you could use some other program to render the lightmaps and import them separately.Static Batching: This feature speeds up the rendering process. Instead of spending time on each frame grouping objects for faster rendering, this allows the system to save the groups generated beforehand. Reducing the number of draw calls is a powerful step towards making a game run faster. That is exactly what this feature does.Render-to-Texture Effects: This is a fun feature, but of limited use. It simply allows you to redirect the rendering of the camera from going to the screen and instead go to a texture. This texture could then, in its most simple form, be put onto a mesh and act like a surveillance camera. You could also do some custom post processing, such as removing the color from the world as the player loses their health. However, that option could become very processor-intensive.Full-Screen Post-Processing Effects: This is another processor-intensive feature that probably will not make it into your mobile game. But you can add some very cool effects to your scene. Such as, adding motion blur when the player is moving really fast, or a vortex effect to warp the scene as the ship passes through a warped section of space. One of the best is using the bloom effect to give things a neon-like glow.Occlusion Culling: This is another great optimization feature. The standard camera system renders everything that is within the camera's view frustum, the view space. Occlusion culling lets us set up volumes in the space our camera can enter. These volumes are used to calculate what the camera can actually see from those locations. If there is a wall in the way, what is the point of rendering everything behind it? Occlusion culling calculates this and stops the camera from rendering anything behind that wall.Navmesh: Dynamic Obstacles and Priority: This feature works in conjunction with the pathfinding system. In scripts, we can dynamically set obstacles, and characters will find their way around them. Being able to set priorities means different types of characters can take different types of objects into consideration when finding their way around. A soldier must go around the barricades to reach his target. The tank, however, could just crash through, should it desire to..Net Socket Support: This feature is only useful if you plan on doing fancy things over a user's network. Multiplayer networking is already supported in every version of Unity. The multiplayer that is available, though, does require a master server. With the use of sockets, one could create connections to other devices locally.Profiler and GPU profiling: This is a very useful feature. The profiler provides tons of information about how much load your game puts on the processor. With this information we can get right down into the nitty-gritties and determine exactly how long a script takes to process. Towards the end of the book, though, we will also create a tool for determining how long specific parts of your code take to process.Script Access to Asset Pipeline: This is an alright feature. With full access to the pipeline, there is a lot of custom processing that can be done on assets and builds. The full range of possibilities are beyond the scope of this book. But think of it as being able to tint all of the imported textures slightly blue.Dark Skin: This is entirely a cosmetic feature. Its point and purpose are questionable. But if a smooth, dark-skinned look is what you desire, this is the feature you want. There is an option in the editor to change it to the color scheme used in Unity Basic. For this feature, whatever floats your boat goes.

Setting up the development environment

Before we can create the next great game for Android, we need to install a few programs. In order to make the Android SDK work, we will first install the JDK. Then, we will be installing the Android SDK. After that is the installation of Unity. We then have to install an optional code editor. To make sure everything is set up correctly, we will connect to our devices and take a look at some special strategies if the device is a tricky one. Finally, we will install Unity Remote, a program that will become invaluable in your mobile development.

Time for action – installing the JDK

Android's development language of choice is Java, so to develop for it we need a copy of the Java SE Development Kit, JDK, on our computers. The process of installing the JDK is given in the following steps:

The latest version of the JDK can be downloaded from http://www.oracle.com/technetwork/java/javase/downloads/index.html. So, open the site in a web browser.Select Java Platform (JDK) from the available versions and you will be brought to a combination of license agreement and type selection page.Accept the license agreement, and select your appropriate Windows version from the bottom of the list. If you are unsure which to choose, then Windows x86 is usually a safe choice.Once the download is completed, run the new installer.A scan, two Next button-clicks, an initialization, and one more Next button will install the JDK to the default location. It is as good there as anywhere else, so once it is done installing, hit Close.

What just happened?

We installed the JDK (Java Development Kit). We need this so that our Android development kit will work. Luckily, the installation process for this keystone is short and sweet.

Time for action – installing the Android SDK

In order to actually develop and connect to our devices, we need to have the Android SDK installed. Having it fulfills two primary requirements. First, it makes sure we have the bulk of the latest drivers for recognizing devices. Second, we are able to use the ADB (Android Debug Bridge). ADB is the system used for actually connecting to and interacting with the device. The process of installing the Android SDK is given in the following steps:

The latest version of the Android SDK can be found at http://developer.android.com/sdk/index.html, so open a web browser and go to the given site.Once there, scroll to the bottom and select USE AN EXISTING IDE.Follow that up by clicking on the Download the SDK Tools for Windows button.You will then be sent to a Terms and Conditions agreement. Read it if you prefer, but agree to it to continue and hit the download button to start downloading the installer.Once it has finished downloading, start it up.Hit the first Next button and the installer will try to find an appropriate version of the JDK. You will come to a page complaining about it, if you do not have it installed.If you skipped ahead and do not have the JDK installed, hit the Visit java.oracle.com button in the middle of the page and go back to the previous section for guidance on installing it. If you do have it, continue with the process.Hitting Next again will bring us to a page about selecting who to install the SDK for.Select Install for anyone using this computer, because the default install location is easier to get to for later purposes.Hit Next twice, followed by Install to install to the default location.Once it is done, hit Next and Finish to complete the installation of the Android SDK Manager.If the Android SDK Manager does not start right away, start it up. Either way, give it a moment to initialize. The SDK Manager makes sure that we have the latest drivers, systems, and tools for developing with the Android platform. But first, we have to actually install them.By default it should select a number of options to install. If not, select the latest Android API, 4.3 (API 18) as of the time of writing this, Android Support Library and Google USB Driver found in Extras. Be absolutely sure that Android SDK Platform-tools is selected. This one will be very important later. It actually includes the tools we need to connect to our device.Once everything is selected, hit Install packages in the bottom-right corner.The next screen is another set of license agreements. Every time a component is installed or updated through the SDK Manager, you have to agree to the license terms before it gets installed. Accept all of the licenses and hit Install to start the process.