IT

Android Game Programming by Example.pdf

DownLoad Book

Published: 2018-04-09 Author:Bieber 25 Browses


Tags: android game

默认图片

Extracting password:f9be24beb7bc47c3


www.allitebooks.comwww.allitebooks.com
Android Game Programming
by Example
Harness the power of the Android SDK by building
three immersive and captivating games
John Horton
BIRMINGHAM - MUMBAI
www.allitebooks.comwww.allitebooks.com
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
www.allitebooks.comwww.allitebooks.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
Sas Editing
Indexer
Tejal Soni
Production Coordinator
Melwyn D'sa
Cover Work
Melwyn D'sa
www.allitebooks.comwww.allitebooks.com
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.
www.allitebooks.comwww.allitebooks.com
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 nd 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.
www.allitebooks.comwww.allitebooks.com
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 rst 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 rst 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.allitebooks.comwww.allitebooks.com
www.PacktPub.com
Support les, eBooks, discount offers, and more
For support les 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 les 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 service@packtpub.com for more details.
At www.PacktPub.com, you can also read a collection of free technical articles, sign up
for a range of free newsletters and receive exclusive discounts and offers on Packt books
and eBooks.
https://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.
www.allitebooks.comwww.allitebooks.com
www.allitebooks.comwww.allitebooks.com
[ i ]
Table of Contents
Preface vii
Chapter 1: Player 1 UP 1
A closer look at the games 2
Tappy Defender 2
Tough retro platformer 3
Asteroids simulator 5
Setting up your development environment 6
Installing the JDK 7
Installing Android Studio 10
Summary 12
Chapter 2: Tappy Defender – First Step 13
Planning the rst game 13
Backstory 13
The game mechanics 14
Rules for the game 15
The design 15
Control 15
Model 16
View 16
Design pattern reality check 16
The game code structure 16
The Android Activity lifecycle 16
The Android Studio le structure 18
Building the home screen 19
Creating the project 19
What we did 20
Building the home screen UI 21
What we did 24
Coding the functionality 24
www.allitebooks.comwww.allitebooks.com
Table of Contents
[ ii ]
Creating GameActivity 27
What we did 27
Conguring the AndroidManifest.xml le 27
What we did 28
Coding the game loop 28
Building the view 28
Creating a new class for the view 29
What we did 30
Structuring the class code 30
The game activity 32
The PlayerShip object 34
Drawing the scene 37
Plotting and drawing 37
Drawing PlayerShip 38
The Canvas and Paint objects 39
Controlling the frame rate 41
Deploying the game 41
Debugging on an Android device 41
Summary 43
Chapter 3: Tappy Defender – Taking Flight 45
Controlling the spaceship 45
Detecting touches 46
Adding boosters to the spaceship 47
Detecting the screen resolution 50
Building the enemies 52
Designing the enemy 53
Spawning the enemy 53
Making the enemy think 55
The thrill of ight – scrolling the background 58
Things that go bump – collision detection 62
Collision detection options 62
Rectangle intersection 62
Radius overlapping 63
The crossing number algorithm 65
Optimizations 65
Multiple hitboxes 65
Neighbor checking 65
Best options for Tappy Defender 66
Summary 70
Table of Contents
[ iii ]
Chapter 4: Tappy Defender – Going Home 71
Displaying a HUD 71
Implementing the rules 74
Ending the game 78
Restarting the game 81
Adding sound FX 82
Generating the FX 82
The SoundPool class 85
Coding the sound FX 85
Adding persistence 87
Iteration 89
Multiple different enemy graphics 89
An exercise in balance 91
Format time 96
Handle the back button 97
The nished game 98
Summary 98
Chapter 5: Platformer – Upgrading the Game Engine 99
The game 100
The backstory 100
The game mechanics 101
Rules for the game 101
Upgrading the game engine 101
The platform activity 101
Locking the layout to landscape 104
The PlatformView class 105
The basic structure of PlatformView 106
The GameObject class 109
The view through a viewport 116
Creating the levels 122
The enhanced update method 131
The enhanced draw method 132
Summary 135
Chapter 6: Platformer – Bob, Beeps, and Bumps 137
The SoundManager class 137
Introducing Bob 141
Multiphase collision detection 150
Player input 157
Animating Bob 165
Summary 171
Table of Contents
[ iv ]
Chapter 7: Platformer – Guns, Life, Money, and the Enemy 173
Ready aim re 173
Pickups 180
The drone 190
The guard 195
Summary 203
Chapter 8: Platformer – Putting It All Together 205
Bullet collision detection 205
Adding some re tiles 207
Eye candy 211
The new platform tiles 212
The new scenery objects 218
Scrolling parallax backgrounds 226
Pause menu with moveable viewport 234
Levels and game rules 236
Traveling between levels 236
The level designs 242
The cave 243
The city 244
The forest 245
The mountains 246
The HUD 247
Summary 248
Chapter 9: Asteroids at 60 FPS with OpenGL ES 2 251
Asteroids simulator 252
The game controls 252
Rules for the game 252
Introducing OpenGL ES 2 252
Why use it and how does it work? 252
What is neat about Version 2? 253
How we will use OpenGL ES 2? 254
Preparing OpenGL ES 2 255
Locking the layout to landscape 255
Activity 255
The view 257
A class to manage our game 258
Managing simple shaders 259
The game's main loop – the renderer 264
Building an OpenGL-friendly, GameObject super class 271
The spaceship 281
Drawing at 60 + FPS 283
Summary 285
Table of Contents
[ v ]
Chapter 10: Move and Draw with OpenGL ES 2 287
Drawing a static game border 287
Twinkling stars 290
Bringing the spaceship to life 293
Rapid re bullets 298
Reusing existing classes 301
Adding the SoundManager class 302
Adding the InputController class 304
Drawing and moving the asteroids 309
Scores and the HUD 314
Adding control buttons 315
Tally icons 319
Life icons 323
Declaring, initializing, and drawing the HUD objects 326
Summary 328
Chapter 11: Things That Go Bump – Part II 329
Planning for collision detection 329
Colliding with the border 330
The rst phase of border collision detection 330
Colliding with an asteroid 331
The crossing number 331
The rst phase and overview of asteroid collision detection 332
The CollisionPackage class 333
Adding collision packages to the objects and making them accessible 336
The CD class outline 341
Implementing radius overlapping for asteroids and ships 342
Implementing rectangle intersection for the border 343
Performing the checks 344
Helper methods 344
Destroying a ship 344
Destroying an asteroid 345
Testing for collisions in update() 346
Precise collision detection with the border 350
Precise collision detection with an asteroid 352
Finishing touches 357
Summary 358
Index 359
[ vii ]
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 difculty is shown in
the text of the book and explained in a straightforward manner.
Steadily build up to implement a exible 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, ring 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.
Preface
[ viii ]
Chapter 2, Tappy Defender – First Step, is about planning the game project and getting
the code for our rst 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 efcient 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 exible 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 nal 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 difcult
levels, and a rapid re gun to the player's spaceship.
Preface
[ ix ]
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 nal 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
Preface
[ x ]
On Mac OS, run Android Studio with Java Runtime Environment (JRE) 6 for
optimized font rendering. You can then congure 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 nd 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, lenames, le extensions,
pathnames, dummy URLs, user input, and Twitter handles are shown as follows:
"We will rst add all the classes, and then update LevelManager in the usual three
places."
Preface
[ xi ]
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."
Warnings or important notes appear in a box like this.
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 feedback@packtpub.com, 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.
www.allitebooks.comwww.allitebooks.com
Preface
[ xii ]
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 les 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 les e-mailed directly to you.
Downloading the color images of this book
We also provide you with a PDF le 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 le 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 nd 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 nd 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 veried, 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 eld. The required
information will appear under the Errata section.
Preface
[ xiii ]
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 copyright@packtpub.com 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
questions@packtpub.com, and we will do our best to address the problem.
[ 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 les to see what is
going on. Also, the entire le 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 les, and the graphical and audio assets are included
in the download as well. The three cool games are progressively more challenging to
implement.
The rst 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
exibility in order to add features.
In the second project, a hard retro platformer, we will see how we can use a simple
and exible design to build a relatively fast and very exible game engine, which is
extendable and reusable. This exibility 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).
Player 1 UP
[ 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 nger to reach your home planet, while avoiding
multiple enemies. Features include:
Basic animation
Home screen
Collision detection
High scores
Simple HUD
Chapter 1
[ 3 ]
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 re caves through the city, forest, and nally 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
Player 1 UP
[ 4 ]
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
Chapter 1
[ 5 ]
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 re 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
Player 1 UP
[ 6 ]
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.
If you already have your preferred development environment ready
to go then jump straight to Chapter 2, Tappy Defender – First Step.
The rst thing we need to do is prepare your PC to develop for Android using Java.
Fortunately, this is made quite simple for us.
Chapter 1
[ 7 ]
If you are learning on Mac or Linux everything in this book will still
work. The next two tutorials have Windows-specic instructions
and screenshots. However, it shouldn't be too difcult to vary the
steps slightly to suit Mac or Linux.
All we need to do is:
1. Install the Java Development Kit (JDK), which allows us to develop in Java.
2. Then install Android Studio to make Android development fast and easy.
Android Studio uses the JDK and some other Android-specic tools that get
automatically installed when we install Android Studio.
Installing the JDK
The rst thing we need to do is get the latest version of the JDK. To complete this
guide, perform the following instructions:
1. We need to be on the Java website, so visit:
http://www.oracle.com/technetwork/java/javase/downloads/index.
html.
2. 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:
www.allitebooks.comwww.allitebooks.com
收藏
分享
暂无回复
Author