Android Game Programming by Example
By John Horton
()
About this ebook
- Implement the critical main game loop and structure your games to enable an array of advanced features
- Animate your characters with sprite sheets, add multiple scrolling parallax backgrounds, and implement genuinely tough, playable levels in your games
- Build super-smooth 60 frames per second with the help of this easy-to-follow, projects-based guide
The book is best suited for existing Android or Java programmers who want to adapt their skills to make exciting Android games.
The book is also for determined readers who might have no Android, game programming or even Java experience, but a reasonable understanding of object oriented programming knowledge is assumed.
John Horton
John Horton is a programming and gaming enthusiast based in the UK. He has a passion for writing apps, games, books, and blog articles. He is the founder of Game Code School.
Read more from John Horton
Learning Java by Building Android Games Rating: 0 out of 5 stars0 ratingsThe Inner Game of Stress: Outsmart Life's Challenges and Fulfill Your Potential Rating: 3 out of 5 stars3/5Beginning C++ Game Programming Rating: 5 out of 5 stars5/5Beginning C++ Game Programming - Second Edition: Learn to program with C++ by building fun games, 2nd Edition Rating: 0 out of 5 stars0 ratingsBuilding E-commerce Sites with VirtueMart Cookbook Rating: 5 out of 5 stars5/5Android Programming for Beginners: Build in-depth, full-featured Android apps starting from zero programming experience Rating: 0 out of 5 stars0 ratingsPrestaShop 1.5 Beginners Guide Rating: 0 out of 5 stars0 ratingsLearning Java by Building Android Games: Learn Java and Android from scratch by building five exciting games Rating: 0 out of 5 stars0 ratingsLearning Java by Building Android Games: Learn Java and Android from scratch by building six exciting games Rating: 0 out of 5 stars0 ratingsAndroid: Game Programming Rating: 0 out of 5 stars0 ratingsPrestaShop 1.3 Beginner's Guide: Build and customize your online store with this speedy, lightweight e-commerce solution Rating: 0 out of 5 stars0 ratingsBeginning C++ Game Programming: Learn C++ from scratch by building fun games Rating: 3 out of 5 stars3/5The Politics of Diversity: Immigration, Resistance, and Change in Monterey Park, California Rating: 0 out of 5 stars0 ratingsAndroid: Programming for Developers Rating: 0 out of 5 stars0 ratings
Related to Android Game Programming by Example
Related ebooks
Learning LibGDX Game Development - Second Edition Rating: 0 out of 5 stars0 ratingsMobile Game Design Essentials Rating: 0 out of 5 stars0 ratingsMastering Android Game Development Rating: 0 out of 5 stars0 ratingsUnity Game Development Scripting Rating: 0 out of 5 stars0 ratingsBuilding an RPG with Unreal Rating: 0 out of 5 stars0 ratingsGameMaker Essentials Rating: 0 out of 5 stars0 ratingsUnity Multiplayer Games Rating: 5 out of 5 stars5/5Learning Android Game Development Rating: 0 out of 5 stars0 ratingsSFML Blueprints Rating: 0 out of 5 stars0 ratingsBuilding Levels in Unity Rating: 0 out of 5 stars0 ratingsGame Development with Swift Rating: 5 out of 5 stars5/5Unity Game Development Blueprints Rating: 0 out of 5 stars0 ratingsUnity AI Programming Essentials Rating: 0 out of 5 stars0 ratingsMastering Unity Scripting Rating: 0 out of 5 stars0 ratingsGame Development with Three.js Rating: 0 out of 5 stars0 ratingsLibGDX Game Development By Example Rating: 0 out of 5 stars0 ratingsLearning Construct 2 Rating: 0 out of 5 stars0 ratingsBeginning C++ Game Programming: Learn C++ from scratch by building fun games Rating: 0 out of 5 stars0 ratingsBuildbox 2.x Game Development Rating: 0 out of 5 stars0 ratingsMonoGame Mastery: Build a Multi-Platform 2D Game and Reusable Game Engine Rating: 0 out of 5 stars0 ratingsHTML5 Games: Novice to Ninja: Create Smash Hit Games in HTML5 Rating: 0 out of 5 stars0 ratingsBuilding a 3D Game with LibGDX Rating: 1 out of 5 stars1/5CRYENGINE Game Development Blueprints Rating: 0 out of 5 stars0 ratingsMastering Unity 5.x Rating: 0 out of 5 stars0 ratingsiOS Game Development By Example Rating: 0 out of 5 stars0 ratingsCreating ELearning Games with Unity Rating: 0 out of 5 stars0 ratingsGame Development Patterns with Unreal Engine 5: Build maintainable and scalable systems with C++ and Blueprint Rating: 0 out of 5 stars0 ratingsBuilding an FPS Game with Unity Rating: 0 out of 5 stars0 ratingsGameMaker Programming By Example Rating: 0 out of 5 stars0 ratings
Computers For You
Standard Deviations: Flawed Assumptions, Tortured Data, and Other Ways to Lie with Statistics Rating: 4 out of 5 stars4/5Elon Musk Rating: 4 out of 5 stars4/5The Invisible Rainbow: A History of Electricity and Life Rating: 5 out of 5 stars5/5Excel 101: A Beginner's & Intermediate's Guide for Mastering the Quintessence of Microsoft Excel (2010-2019 & 365) in no time! Rating: 0 out of 5 stars0 ratingsHow to Create Cpn Numbers the Right way: A Step by Step Guide to Creating cpn Numbers Legally Rating: 4 out of 5 stars4/5The ChatGPT Millionaire Handbook: Make Money Online With the Power of AI Technology Rating: 4 out of 5 stars4/5The Innovators: How a Group of Hackers, Geniuses, and Geeks Created the Digital Revolution Rating: 4 out of 5 stars4/5Deep Search: How to Explore the Internet More Effectively Rating: 5 out of 5 stars5/5Mastering ChatGPT: 21 Prompts Templates for Effortless Writing Rating: 4 out of 5 stars4/5Alan Turing: The Enigma: The Book That Inspired the Film The Imitation Game - Updated Edition Rating: 4 out of 5 stars4/5An Ultimate Guide to Kali Linux for Beginners Rating: 3 out of 5 stars3/5Procreate for Beginners: Introduction to Procreate for Drawing and Illustrating on the iPad Rating: 5 out of 5 stars5/5Slenderman: Online Obsession, Mental Illness, and the Violent Crime of Two Midwestern Girls Rating: 4 out of 5 stars4/5CompTIA IT Fundamentals (ITF+) Study Guide: Exam FC0-U61 Rating: 0 out of 5 stars0 ratingsUncanny Valley: A Memoir Rating: 4 out of 5 stars4/5CompTIA Security+ Get Certified Get Ahead: SY0-701 Study Guide Rating: 5 out of 5 stars5/5The Hacker Crackdown: Law and Disorder on the Electronic Frontier Rating: 4 out of 5 stars4/5Master Builder Roblox: The Essential Guide Rating: 4 out of 5 stars4/5SQL QuickStart Guide: The Simplified Beginner's Guide to Managing, Analyzing, and Manipulating Data With SQL Rating: 4 out of 5 stars4/5Technical Writing For Dummies Rating: 0 out of 5 stars0 ratingsSome Future Day: How AI Is Going to Change Everything Rating: 0 out of 5 stars0 ratingsTor and the Dark Art of Anonymity Rating: 5 out of 5 stars5/5Everybody Lies: Big Data, New Data, and What the Internet Can Tell Us About Who We Really Are Rating: 4 out of 5 stars4/5Grokking Algorithms: An illustrated guide for programmers and other curious people Rating: 4 out of 5 stars4/5
Reviews for Android Game Programming by Example
0 ratings0 reviews
Book preview
Android Game Programming by Example - John Horton
Table of Contents
Android Game Programming by Example
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. Player 1 UP
A closer look at the games
Tappy Defender
Tough retro platformer
Asteroids simulator
Setting up your development environment
Installing the JDK
Installing Android Studio
Summary
2. Tappy Defender – First Step
Planning the first game
Backstory
The game mechanics
Rules for the game
The design
Control
Model
View
Design pattern reality check
The game code structure
The Android Activity lifecycle
The Android Studio file structure
Building the home screen
Creating the project
What we did
Building the home screen UI
What we did
Coding the functionality
Creating GameActivity
What we did
Configuring the AndroidManifest.xml file
What we did
Coding the game loop
Building the view
Creating a new class for the view
What we did
Structuring the class code
The game activity
The PlayerShip object
Drawing the scene
Plotting and drawing
Drawing PlayerShip
The Canvas and Paint objects
Controlling the frame rate
Deploying the game
Debugging on an Android device
Summary
3. Tappy Defender – Taking Flight
Controlling the spaceship
Detecting touches
Adding boosters to the spaceship
Detecting the screen resolution
Building the enemies
Designing the enemy
Spawning the enemy
Making the enemy think
The thrill of flight – scrolling the background
Things that go bump – collision detection
Collision detection options
Rectangle intersection
Radius overlapping
The crossing number algorithm
Optimizations
Multiple hitboxes
Neighbor checking
Best options for Tappy Defender
Summary
4. Tappy Defender – Going Home
Displaying a HUD
Implementing the rules
Ending the game
Restarting the game
Adding sound FX
Generating the FX
The SoundPool class
Coding the sound FX
Adding persistence
Iteration
Multiple different enemy graphics
An exercise in balance
Format time
Handle the back button
The finished game
Summary
5. Platformer – Upgrading the Game Engine
The game
The backstory
The game mechanics
Rules for the game
Upgrading the game engine
The platform activity
Locking the layout to landscape
The PlatformView class
The basic structure of PlatformView
The GameObject class
The view through a viewport
Creating the levels
The enhanced update method
The enhanced draw method
Summary
6. Platformer – Bob, Beeps, and Bumps
The SoundManager class
Introducing Bob
Multiphase collision detection
Player input
Animating Bob
Summary
7. Platformer – Guns, Life, Money, and the Enemy
Ready aim fire
Pickups
The drone
The guard
Summary
8. Platformer – Putting It All Together
Bullet collision detection
Adding some fire tiles
Eye candy
The new platform tiles
The new scenery objects
Scrolling parallax backgrounds
Pause menu with moveable viewport
Levels and game rules
Traveling between levels
The level designs
The cave
The city
The forest
The mountains
The HUD
Summary
9. Asteroids at 60 FPS with OpenGL ES 2
Asteroids simulator
The game controls
Rules for the game
Introducing OpenGL ES 2
Why use it and how does it work?
What is neat about Version 2?
How we will use OpenGL ES 2?
Preparing OpenGL ES 2
Locking the layout to landscape
Activity
The view
A class to manage our game
Managing simple shaders
The game's main loop – the renderer
Building an OpenGL-friendly, GameObject super class
The spaceship
Drawing at 60 + FPS
Summary
10. Move and Draw with OpenGL ES 2
Drawing a static game border
Twinkling stars
Bringing the spaceship to life
Rapid fire bullets
Reusing existing classes
Adding the SoundManager class
Adding the InputController class
Drawing and moving the asteroids
Scores and the HUD
Adding control buttons
Tally icons
Life icons
Declaring, initializing, and drawing the HUD objects
Summary
11. Things That Go Bump – Part II
Planning for collision detection
Colliding with the border
The first phase of border collision detection
Colliding with an asteroid
The crossing number
The first phase and overview of asteroid collision detection
The CollisionPackage class
Adding collision packages to the objects and making them accessible
Adding a collision package to the Bullet class
Adding a collision package to the SpaceShip class
Adding a collision package to the Asteroid class
The CD class outline
Implementing radius overlapping for asteroids and ships
Implementing rectangle intersection for the border
Performing the checks
Helper methods
Destroying a ship
Destroying an asteroid
Testing for collisions in update()
Precise collision detection with the border
Precise collision detection with an asteroid
Finishing touches
Summary
Index
Android Game Programming by Example
Android Game Programming by Example
Copyright © 2015 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: June 2015
Production reference: 1250615
Published by Packt Publishing Ltd.
Livery Place
35 Livery Street
Birmingham B3 2PB, UK.
ISBN 978-1-78528-012-2
www.packtpub.com
Credits
Author
John Horton
Reviewers
Håvard Kindem
José Rodriguez-Rivas
Commissioning Editor
Nadeem N. Bagban
Acquisition Editor
Tushar Gupta
Content Development Editor
Siddhesh Salvi
Technical Editor
Prajakta Mhatre
Copy Editor
Charlotte Carneiro
Project Coordinator
Nidhi Joshi
Proofreader
Safis Editing
Indexer
Tejal Soni
Production Coordinator
Melwyn D'sa
Cover Work
Melwyn D'sa
About the Author
John Horton is a technology enthusiast based in the UK. When he is not creating apps and writing books or blog articles for http://www.gamecodeschool.com, he can be found playing or making video games with his two sons.
About the Reviewers
Håvard Kindem is a game developer from Norway who has a long-lived passion for games and game development. He started programming at an early age, which later resulted in an MSc in game technology. During his studies, Håvard became the founding member and CEO of Fallen Leaves Interactive, a group focusing on PC, Xbox, and Android development. The company made games for clients such as KLM Royal Dutch Airlines and contributed to Games4Health.
Currently, Håvard is employed at the National Lottery Association in Norway, where he works as a concept developer. In order to find new exciting products for its about 2.8 million customers, he has, among other things, worked on and published multiple mobile games. Håvard remains an avid gamer, and when he is not busy releasing a new project, he loves to return to the old classics or spend the evenings playing his bass guitar.
I would like to thank my mentor, Simon McCallum, for always challenging me and pushing me toward new technologies. I would also like to thank my nephew and niece for being my motivation and allowing me to stay a kid forever; I love you guys! Last but not least, I would like to thank my partner in crime, Sara, for her support and striving for perfection.
José Rodriguez-Rivas is a young game developer. He loves to dream big about his future, often picturing himself as a head developer for a huge game company that he started. He first started developing games using RPG Maker VX Ace when he was in the eighth grade. As soon as he got into high school, he wanted to learn how to actually program a video game. He first learned Java with the libGDX framework, which allows him to port his games to both PC and Android. He is really into web design as well, and has designed two websites, one for his own company, Tiny Country Games (https://tinycountrygames.com/), and another for the Young Entrepreneurs Association of California, YEACAL (http://yeacal.org/). He enjoys learning new things, even if they don't directly relate to game development. For example, he likes to practice instruments such as the guitar, ukulele, and electric bass.
First of all, I would thank my computer science teacher, Mark Sheinberg, for always pushing me to improve my coding skills and learn new things. I would like to thank my best friend, Charli-Anne Hanna-Baker, for always supporting my work and keeping my morale high with her amazing attitude. Annika Pašeta, thank you for giving me the opportunity of being the webmaster of YEACAL, which inspired me to learn ASP.NET and C#. Last but not least, I would like to thank my family for their constant support and love.
www.PacktPub.com
Support files, eBooks, discount offers, and more
For support files and downloads related to your book, please visit www.PacktPub.com.
Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at
At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters and receive exclusive discounts and offers on Packt books and eBooks.
https://www2.packtpub.com/books/subscription/packtlib
Do you need instant solutions to your IT questions? PacktLib is Packt's online digital book library. Here, you can search, access, and read Packt's entire library of books.
Why subscribe?
Fully searchable across every book published by Packt
Copy and paste, print, and bookmark content
On demand and accessible via a 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 9 entirely free books. Simply use your login credentials for immediate access.
Preface
Making games is addictive and very rewarding, it can be hard to stop once you get started. The problem comes when we reach a stumbling block because we don't know how to implement a feature, or perhaps integrate it into our game. This book is a whirlwind tour of as many Android 2D gaming features that can possibly be squeezed into 11 chapters.
Every line of the code used to build three games of increasing difficulty is shown in the text of the book and explained in a straightforward manner.
Steadily build up to implement a flexible and advanced game engine that uses OpenGL ES 2 for fast smooth frame rates. This is achieved by starting with a simple game and gradually increasing the complexity of the three complete games built step by step.
Implement cool features like sprite sheet character animation and scrolling parallax backgrounds. Design and implement genuinely challenging and playable platform game levels.
Learn to code both basic and advanced collision detection. Make simple the math behind 2D rotation, velocity, and collision. Run your game designs at 60 frames per second or better.
Process multi-touch screen input. Implement a multitude of other game features like pickups, firing weapons, HUDs, generating and playing sound FX, scenery, level transition, high scores, and more.
What this book covers
Chapter 1, Player 1 UP, is an introduction to the three cool games that we will build. We will also get the development environment set up.
Chapter 2, Tappy Defender – First Step, is about planning the game project and getting the code for our first game engine up and running. We will implement a main game loop, control the frame rate, and draw to the screen.
Chapter 3, Tappy Defender – Taking Flight, teaches us to add lots of new objects and some features like player controls, enemies, and scrolling stars in the background. In the Things that go bump – collision detection section, we will discuss our collision detection options and implement an efficient solution for this game.
Chapter 4, Tappy Defender – Going Home, completes the game, including adding high scores, victory conditions, sound FX, and more.
Chapter 5, Platformer – Upgrading the Game Engine, provides a good understanding of what is needed in a simple game engine. We can quickly learn about and build a more advanced and flexible engine, suitable for a really tough, retro 2D platform game.
Chapter 6, Platformer – Bob, Beeps, and Bumps, uses our new game engine to add a class to manage the sound FX and a class to implement the more complex player controls that are required by a game of this type. We can then make Bob, our playable character, an animated running, jumping hero.
Chapter 7, Platformer – Guns, Life, Money, and the Enemy, continues the subject of the previous two chapters; we add a ton of features in this one. We will add collectible pick-ups and power-ups, a deadly homing enemy, and a patrolling guard. Of course with all this, Bob is going to need a machine gun to defend himself, and he gets one!
Chapter 8, Platformer – Putting It All Together, is where our platform game comes to life. We will add lots of new platform tile types and scenery objects, multiple scrolling parallax backgrounds, collision detection, and a teleporting system so that Bob can travel between the levels of the game. Using our range of tile types, scenery objects, and backgrounds, we will implement four playable levels linked together by the teleporting system.
Chapter 9, Asteroids at 60 FPS with OpenGL ES 2, contains the final project of this book, which is an introduction to 2D games with the super fast OpenGL graphics library. In this chapter, we will quickly learn how to draw with OpenGL ES 2 and integrate the drawing system into our game engine. By the end of the chapter, we will have a working engine that draws an Asteroids-style spaceship to the screen.
Chapter 10, Move and Draw with OpenGL ES 2, is where we will quickly integrate our sound and control systems from the previous project. Then, we can add a game border, twinkling star system, spinning asteroids, a neat HUD, progressively difficult levels, and a rapid fire gun to the player's spaceship.
Chapter 11, Things That Go Bump – Part II, completes the Asteroids game by adding the collision detection. The math required to detect collisions with the irregularly-shaped spinning asteroids is made simple and implemented into the game engine. By the end of this chapter, you will have the third and final fully playable game.
What you need for this book
Any recent and free version of Eclipse or Android Studio running on any of the major operating systems can use the code in this book.
Android Studio is the recommended development tool, and at time of publication, the minimum system requirements are:
For Windows:
Microsoft Windows 8/7/Vista/2003 (32 or 64-bit)
2 GB RAM minimum, 4 GB RAM recommended
400 MB hard disk space
At least 1 GB for Android SDK, emulator system images, and caches
1280 x 800 minimum screen resolution
Java Development Kit (JDK) 7
Optional for accelerated emulator: Intel processor with support for Intel VT-x, Intel EM64T (Intel 64), and Execute Disable (XD) Bit functionality
For Mac OS X:
Mac OS X 10.8.5 or higher, up to 10.9 (Mavericks)
2 GB RAM minimum, 4 GB RAM recommended
400 MB hard disk space
At least 1 GB for Android SDK, emulator system images, and caches
1280 x 800 minimum screen resolution
Java Runtime Environment (JRE) 6
Java Development Kit (JDK) 7
Optional for accelerated emulator: Intel processor with support for Intel VT-x, Intel EM64T (Intel 64), and Execute Disable (XD) Bit functionality
On Mac OS, run Android Studio with Java Runtime Environment (JRE) 6 for optimized font rendering. You can then configure your project to use JDK 6 or JDK 7.
For Linux:
GNOME or KDE desktop
GNU C Library (glibc) 2.15 or later
2 GB RAM minimum, 4 GB RAM recommended
400 MB hard disk space
At least 1 GB for Android SDK, emulator system images, and caches
1280 x 800 minimum screen resolution
Oracle Java Development Kit (JDK) 7
Tested on Ubuntu 14.04, Trusty Tahr (64-bit distribution capable of running 32-bit applications).
Who this book is for
The book is best suited for existing Android or Java programmers, who want to adapt their skills to make exciting Android games.
The book is also for readers who might have no Android, game programming, or even Java experience, but a good understanding of object-oriented programming is assumed.
Also, a determined programming beginner with at least some OOP experience can follow along and build all the projects, because of the step-by-step approach of the book. This book will also be ideally suited for readers who have completed Learning Java By Building Android Games.
Conventions
In this book, you will find a number of text styles that distinguish between different kinds of information. Here are some examples of these styles and an explanation of their meaning.
Code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles are shown as follows: We will first add all the classes, and then update LevelManager in the usual three places.
A block of code is set as follows:
if (lm.isPlaying()) {
// Reset the players location as
// the world centre of the viewport
//if game is playing
vp.setWorldCentre(lm.gameObjects.get(lm.playerIndex)
.getWorldLocation().x,
lm.gameObjects.get(lm.playerIndex)
.getWorldLocation().y);
When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:
//Has player fallen out of the map? if (lm.player.getWorldLocation().x < 0 || lm.player.getWorldLocation().x > lm.mapWidth || lm.player.getWorldLocation().y > lm.mapHeight) {
New terms and important words are shown in bold. Words that you see on the screen, for example, in menus or dialog boxes, appear in the text like this: In the Create New Project window shown next, we need to enter some basic information about our app.
Note
Warnings or important notes appear in a box like this.
Tip
Tips and tricks appear like this.
Reader feedback
Feedback from our readers is always welcome. Let us know what you think about this book—what you liked or disliked. Reader feedback is important for us as it helps us develop titles that you will really get the most out of.
To send us general feedback, simply e-mail <[email protected]>, and mention the book's title in the subject of your message.
If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide at www.packtpub.com/authors.
Customer support
Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.
Downloading the example code
You can download the example code files from your account at http://www.packtpub.com for all the Packt Publishing books you have purchased. 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 better understand the changes in the output. You can download this file from: https://www.packtpub.com/sites/default/files/downloads/0122OS_ColoredImages.pdf.
Errata
Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books—maybe a mistake in the text or the code—we would be grateful if you could report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded to our website or added to any list of existing errata under the Errata section of that title.
To view the previously submitted errata, go to https://www.packtpub.com/books/content/support and enter the name of the book in the search field. The required information will appear under the Errata section.
Piracy
Piracy of copyrighted material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works in any form on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy.
Please contact us at <[email protected]> with a link to the suspected pirated material.
We appreciate your help in protecting our authors and our ability to bring you valuable content.
Questions
If you have a problem with any aspect of this book, you can contact us at <[email protected]>, and we will do our best to address the problem.
Chapter 1. Player 1 UP
The terminology used by old arcade and pinball machines 1 UP
was a kind of notice to the players that they were playing (up) now. It was also used to indicate earning an extra life. Are you ready to build three great games?
We will build three cool games together. Every line of code for these three games is shown in this book; you will never have to refer to the code files to see what is going on. Also, the entire file set required to build all three games is included in the download bundle that can be obtained from the books page on the Packt website.
All the code, Android manifest files, and the graphical and audio assets are included in the download as well. The three cool games are progressively more challenging to implement.
The first project uses a simple but functional game engine that clearly demonstrates the essentials of a main game loop. The game will be fully working with the home screen, high scores, sound, and animation. But by the end of the project, as we add features and try to balance the game play, we will soon see that we need more flexibility in order to add features.
In the second project, a hard retro platformer, we will see how we can use a simple and flexible design to build a relatively fast and very flexible game engine, which is extendable and reusable. This flexibility will allow us to make quite a complex and well-featured game. This game will have multiple levels, different environments, and more. This in turn will highlight the need for being able to draw graphics more quickly. That leads us on to the third project.
In the third project, we will build an Asteroids-like game called Asteroids simulator. Although the game won't have as many features as the previous project, it will feature the super-smooth drawing of hundreds of animated game objects running at over 60 frames per second. We will achieve this by learning about and using the Open Graphics Library for Embedded Systems (OpenGL ES 2).
By the end of this book, you will have a whole repertoire of design ideas, techniques, and code templates that you can use in your future games. By seeing the strengths and weaknesses of the different ways of making games on Android, you will be able to successfully design and build games in the most appropriate way for your next big game.
A closer look at the games
Here is a quick glimpse at the three projects.
Tappy Defender
Fly Flappy Bird-style with one finger to reach your home planet, while avoiding multiple enemies. Features include:
Basic animation
Home screen
Collision detection
High scores
Simple HUD
One-finger touch screen controls
Tough retro platformer
This is a genuinely tough-to-beat retro style platform game. We have to guide Bob from the underground fire caves through the city, forest, and finally to the mountains. It has four challenging levels. Features include:
A more advanced, flexible game engine
More advanced sprite sheet
character animation
A level builder engine to design your levels in text format
Multiple scrolling parallax backgrounds
Transition between levels
A more advanced HUD
Add loads of extra diverse levels
Sound manager to easily manage sound FX
Pickups
An upgradeable gun
Seek-and-destroy enemy drones
Simple AI scripting for patrolling enemy guards
Hazards such as fire pits
Scenery objects to create atmosphere
Asteroids simulator
This is a classic shooter with retro vector-graphics style visuals. It involves clearing waves of smoothly animated spinning asteroids with a rapid fire gun. Features include:
60 frames per second or better, even on old hardware
An introduction to OpenGL ES 2
Shooter with waves of progressive difficulty
Advanced multiphase collision detection
Setting up your development environment
All the code in this book and the download bundle will work in your favorite Android IDE. However, I found the latest version of Android Studio exceptionally friendly to use and the code was written and tested in it as well.
If you don't currently use Android Studio, I encourage you to give it a try. Here is a quick overview of how to get up and running quickly. This guide includes steps to install the Java JDK in case you are completely new to Android development.
Tip
If you already have your preferred development environment ready to go then jump straight to Chapter 2, Tappy Defender – First Step.
The first thing we need to do is prepare your PC to develop for Android using Java. Fortunately, this is made quite simple for us.
Tip
If you are learning on Mac or Linux everything in this book will still work. The next two tutorials have Windows-specific instructions and screenshots. However, it shouldn't be too difficult to vary the steps slightly to suit Mac or Linux.
All we need to do is:
Install the Java Development Kit (JDK), which allows us to develop in Java.
Then install Android Studio to make Android development fast and easy. Android Studio uses the JDK and some other Android-specific tools that get automatically installed when we install Android Studio.
Installing the JDK
The first thing we need to do is get the latest version of the JDK. To complete this guide, perform the following instructions:
We need to be on the Java website, so visit: http://www.oracle.com/technetwork/java/javase/downloads/index.html.
Find the three buttons shown here and click on the one that says JDK that is highlighted in the following image. They are on the right-hand side of the web page. Then, click on the Download button under the JDK option:
You will be taken to a page that has multiple options to download the JDK. In the Product/File Description column, you need to click the option that matches your operating system. Windows, Mac, Linux, and some other less common options are all listed.
A common question asked here is, do I have 32- or 64-bit windows? To find out, right-click on your My Computer icon (This PC on Windows 8), click on the Properties option, and look under the System heading at the System type entry:
Click on the somewhat hidden Accept License Agreement checkbox:
Now, click on download for your OS and type as previously determined. Wait for the download to finish.
In your downloads folder, double-click on the file you just downloaded. The latest version at the time of writing for a 64-bit Windows PC was jdk-8u5-windows-x64. If you are using Mac/Linux or have a 32-bit OS, your filename will vary accordingly.
In the first of several install dialogs, click on the Next button and you will see the following dialog box:
Accept