i Beginning Android 4 Games Development ■ ■ ■ Mario Zechner Robert Green Beginning Android 4 Games Development Copyright © 2011 by Mario Zechner and Robert Green All rights reserved. No part of this work may be reproduced or transmitted in any form or by any means, electronic or mechanical, including photocopying, recording, or by any information storage or retrieval system, without the prior written permission of the copyright owner and the publisher. ISBN-13 (pbk): 978-1-4302-3987-1 ISBN-13 (electronic): 978-1-4302-3988-8 Trademarked names, logos, and images may appear in this book. Rather than use a trademark symbol with every occurrence of a trademarked name, logo, or image, we use the names, logos, and images only in an editorial fashion and to the benefit of the trademark owner, with no intention of infringement of the trademark. The images of the Android Robot (01 / Android Robot) are reproduced from work created and shared by Google and used according to terms described in the Creative Commons 3.0 Attribution License. Android and all Android and Google-based marks are trademarks or registered trademarks of Google, Inc., in the U.S. and other countries. Apress Media, L.L.C. is not affiliated with Google, Inc., and this book was written without endorsement from Google, Inc. The use in this publication of trade names, trademarks, service marks, and similar terms, even if they are not identified as such, is not to be taken as an expression of opinion as to whether or not they are subject to proprietary rights. President and Publisher: Paul Manning Lead Editor: Steve Anglin Development Editor: Gary Schwartz Editorial Board: Steve Anglin, Mark Beckner, Ewan Buckingham, Gary Cornell, Morgan Engel, Jonathan Gennick, Jonathan Hassell, Robert Hutchinson, Michelle Lowman, James Markham, Matthew Moodie, Jeff Olson, Jeffrey Pepper, Douglas Pundick, Ben Renow-Clarke, Dominic Shakeshaft, Gwenan Spearing, Matt Wade, Tom Welsh Coordinating Editor: Adam Heath Copy Editor: Chandra Clarke Compositor: MacPS, LLC Indexer: BIM Indexing & Proofreading Services Artist: SPi Global Cover Designer: Anna Ishchenko Distributed to the book trade worldwide by Springer Science+Business Media, LLC., 233 Spring Street, 6th Floor, New York, NY 10013. Phone 1-800-SPRINGER, fax (201) 348-4505, e-mail orders-ny@springer-sbm.com, or visit www.springeronline.com. For information on translations, please e-mail rights@apress.com, or visit www.apress.com. Apress and friends of ED books may be purchased in bulk for academic, corporate, or promotional use. eBook versions and licenses are also available for most titles. For more information, reference our Special Bulk Sales–eBook Licensing web page at www.apress.com/bulk-sales. The information in this book is distributed on an “as is” basis, without warranty. Although every precaution has been taken in the preparation of this work, neither the author(s) nor Apress shall have any liability to any person or entity with respect to any loss or damage caused or alleged to be caused directly or indirectly by the information contained in this work. Any source code or other supplementary materials referenced by the author in this text is available to readers at www.apress.com. For detailed information about how to locate your book’s source code, go to http://www.apress.com/source-code/. Dedicated to our idols, fans, families, and loved ones iv Contents at a Glance Contents v About the Authors . xii Acknowledgments . xiii Introduction xiv ■Chapter 1: Android, the New Kid on the Block 1 ■Chapter 2: First Steps with the Android SDK . 25 ■Chapter 3: Game Development 101 . 53 ■Chapter 4: Android for Game Developers 107 ■Chapter 5: An Android Game Development Framework 195 ■Chapter 6: Mr. Nom Invades Android 239 ■Chapter 7: OpenGL ES: A Gentle Introduction 279 ■Chapter 8: 2D Game Programming Tricks . 357 ■Chapter 9: Super Jumper: A 2D OpenGL ES Game . 435 ■Chapter 10: OpenGL ES: Going 3D 495 ■Chapter 11: 3D Programming Tricks . 533 ■Chapter 12: Droid Invaders: The Grand Finale . 587 ■Chapter 13: Publishing Your Game 635 ■Chapter 14: What’s Next? 647 Index . 653 v Contents Contents at a Glance iv About the Authors . xii Acknowledgments . xiii Introduction xiv ■Chapter 1: Android, the New Kid on the Block 1 A Brief History of Android . 2 Fragmentation . 3 The Role of Google 4 The Android Open Source Project 4 The Android Market . 4 Challenges, Device Seeding, and Google I/O . 5 Android’s Features and Architecture 6 The Kernel 7 The Runtime and Dalvik . 7 System Libraries 8 The Application Framework . 9 The Software Development Kit . 10 The Developer Community 11 Devices, Devices, Devices! . 12 Hardware . 12 The Range of Devices 14 Compatibility Across All Devices . 19 Mobile Gaming Is Different . 20 A Gaming Machine in Every Pocket . 20 Always Connected . 21 Casual and Hardcore 22 Big Market, Small Developers 22 Summary 23 ■Chapter 2: First Steps with the Android SDK . 25 Setting Up the Development Environment 25 Setting Up the JDK . 26 Setting Up the Android SDK . 26 ■ CONTENTS vi Installing Eclipse 28 Installing the ADT Eclipse Plug-In 28 A Quick Tour of Eclipse 30 Helpful Eclipse Shortcuts . 32 Hello World, Android Style 33 Creating the Project . 33 Exploring the Project 34 Writing the Application Code . 36 Running and Debugging Android Applications 39 Connecting a Device 39 Creating an Android Virtual Device 39 Running an Application 41 Debugging an Application 44 LogCat and DDMS 48 Using ADB 50 Summary 51 ■Chapter 3: Game Development 101 . 53 Genres: To Each One’s Taste 54 Casual Games 54 Puzzle Games . 56 Action and Arcade Games 58 Tower-Defense Games 61 Innovation 62 Game Design: The Pen Is Mightier Than the Code 63 Core Game Mechanics . 64 A Story and an Art Style . 66 Screens and Transitions 67 Code: The Nitty-Gritty Details 73 Application and Window Management 74 Input . 75 File I/O 79 Audio 79 Graphics . 84 The Game Framework 97 Summary 105 ■Chapter 4: Android for Game Developers 107 Defining an Android Application: The Manifest File 108 The <manifest> Element . 109 The <application> Element . 110 The <activity> Element . 111 The <uses-permission> Element 113 The <uses-feature> Element . 114 The <uses-sdk> Element 116 Android Game Project Setup in Ten Easy Steps . 117 Market Filters . 119 Defining the Icon of Your Game . 119 Android API Basics 121 ■ CONTENTS vii Creating a Test Project 121 The Activity Life Cycle 125 Input Device Handling 132 File Handling 152 Audio Programming . 158 Playing Sound Effects 159 Streaming Music 163 Basic Graphics Programming 167 Best Practices . 192 Summary 193 ■Chapter 5: An Android Game Development Framework 195 Plan of Attack 195 The AndroidFileIO Class 196 AndroidAudio, AndroidSound, and AndroidMusic: Crash, Bang, Boom! . 197 AndroidInput and AccelerometerHandler 202 AccelerometerHandler: Which Side Is Up? 202 CompassHandler . 204 The Pool Class: Because Reuse Is Good for You! . 205 KeyboardHandler: Up, Up, Down, Down, Left, Right . . . 207 Touch Handlers 211 AndroidInput: The Great Coordinator . 219 AndroidGraphics and AndroidPixmap: Double Rainbow . 221 Handling Different Screen Sizes and Resolutions 221 AndroidPixmap: Pixels for the People 226 AndroidGraphics: Serving Our Drawing Needs 227 AndroidFastRenderView: Loop, Stretch, Loop, Stretch 231 AndroidGame: Tying Everything Together . 234 Summary 238 ■Chapter 6: Mr. Nom Invades Android 239 Creating the Assets . 239 Setting Up the Project . 241 MrNomGame: The Main Activity . 242 Assets: A Convenient Asset Store 242 Settings: Keeping Track of User Choices and High Scores 243 LoadingScreen: Fetching the Assets from Disk . 246 The Main Menu Screen . 247 The HelpScreen Class(es) . 251 The High-Scores Screen . 253 Rendering Numbers: An Excursion 253 Implementing the Screen . 255 Abstracting… . 257 Abstracting the World of Mr. Nom: Model, View, Controller 258 The GameScreen Class 270 Summary 277 ■Chapter 7: OpenGL ES: A Gentle Introduction 279 What is OpenGL ES and Why Should I Care? 279 The Programming Model: An Analogy 280 ■ CONTENTS viii Projections . 282 Normalized Device Space and the Viewport 284 Matrices . 284 The Rendering Pipeline 285 Before We Begin . 286 GLSurfaceView: Making Things Easy Since 2008 . 287 GLGame: Implementing the Game Interface . 290 Look Mom, I Got a Red Triangle! . 297 Defining the Viewport 298 Defining the Projection Matrix . 298 Specifying Triangles 302 Putting It Together . 306 Specifying Per Vertex Color 309 Texture Mapping: Wallpapering Made Easy 313 Texture Coordinates . 313 Uploading Bitmaps . 315 Texture Filtering . 316 Disposing of Textures 317 A Helpful Snippet . 318 Enabling Texturing . 318 Putting It Together . 318 A Texture Class 321 Indexed Vertices: Because Re-use is Good for You 323 Putting It Together . 324 A Vertices Class . 326 Alpha Blending: I Can See Through You 329 More Primitives: Points, Lines, Strips, and Fans 333 2D Transformations: Fun with the Model-View Matrix . 334 World and Model Space . 334 Matrices Again . 335 An Initial Example Using Translation . 336 More Transformations . 341 Optimizing for Performance 345 Measuring Frame Rate . 345 The Curious Case of the Hero on Android 1.5 347 What’s Making My OpenGL ES Rendering So Slow? 347 Removing Unnecessary State Changes . 349 Reducing Texture Size Means Fewer Pixels to be Fetched . 351 Reducing Calls to OpenGL ES/JNI Methods . 352 The Concept of Binding Vertices 352 In Closing . 356 Summary 356 ■Chapter 8: 2D Game Programming Tricks . 357 Before We Begin . 357 In the Beginning . . . There Was the Vector . 358 Working with Vectors . 359 A Little Trigonometry . 361 Implementing a Vector Class . 363 ■ CONTENTS ix A Simple Usage Example . 366 A Little Physics in 2D 371 Newton and Euler, Best Friends Forever . 371 Force and Mass . 372 Playing Around, Theoretically 373 Playing Around, Practically 374 Collision Detection and Object Representation in 2D 378 Bounding Shapes . 379 Constructing Bounding Shapes 381 Game Object Attributes 383 Broad-Phase and Narrow-Phase Collision Detection . 384 An Elaborate Example 391 A Camera in 2D . 404 The Camera2D Class 407 An Example 409 Texture Atlas: Because Sharing Is Caring . 410 An Example 412 Texture Regions, Sprites, and Batches: Hiding OpenGL ES 416 The TextureRegion Class . 417 The SpriteBatcher Class 418 Sprite Animation . 427 The Animation Class 428 An Example 429 Summary 433 ■Chapter 9: Super Jumper: A 2D OpenGL ES Game . 435 Core Game Mechanics 435 A Backstory and Art Style . 436 Screens and Transitions . 437 Defining the Game World 438 Creating the Assets . 441 The UI Elements . 441 Handling Text with Bitmap Fonts . 443 The Game Elements . 445 Texture Atlas to the Rescue . 447 Music and Sound . 448 Implementing Super Jumper 449 The Assets Class 450 The Settings Class . 453 The Main Activity . 454 The Font Class . 456 GLScreen 457 The Main Menu Screen 458 The Help Screens . 461 The High-Scores Screen 463 The Simulation Classes 466 The Game Screen . 481 The WorldRenderer Class 489 . the copyright owner and the publisher. ISBN- 13 (pbk): 978-1- 430 2 -39 87-1 ISBN- 13 (electronic): 978-1- 430 2 -39 88-8 Trademarked names, logos, and images may. 33 3 2D Transformations: Fun with the Model-View Matrix . 33 4