Mario Zechner,

J. F. DiMarzio and

Robert Green

Beginning Android Games

3rd ed.

Mario Zechner

Graz, Steiermark, Austria

J. F. DiMarzio

Celebration, Florida, USA

Robert Green

Portland, Oregon, USA

Any source code or other supplementary materials referenced by the author in this text are available to readers at www.apress.com . For detailed information about how to locate your book’s source code, go to www.apress.com/source-code/ . Readers can also access source code at SpringerLink in the Supplementary Material section for each chapter.

ISBN 978-1-4842-0473-3

e-ISBN 978-1-4842-0472-6

DOI 10.1007/978-1-4842-0472-6

Library of Congress Control Number: 2016961227

© Mario Zechner, J.F. DiMarzio and Robert Green 2016

This work is subject to copyright. All rights are reserved by the Publisher, whether the whole or part of the material is concerned, specifically the rights of translation, reprinting, reuse of illustrations, recitation, broadcasting, reproduction on microfilms or in any other physical way, and transmission or information storage and retrieval, electronic adaptation, computer software, or by similar or dissimilar methodology now known or hereafter developed.

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 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.

While the advice and information in this book are believed to be true and accurate at the date of publication, neither the authors nor the editors nor the publisher can accept any legal responsibility for any errors or omissions that may be made. The publisher makes no warranty, express or implied, with respect to the material contained herein.

Printed on acid-free paper

Distributed to the book trade worldwide by Springer Science+Business Media New York, 233 Spring Street, 6th Floor, New York, NY 10013. Phone 1-800-SPRINGER, fax (201) 348-4505, e-mail [email protected], or visit www.springeronline.com. Apress Media, LLC is a California LLC and the sole member (owner) is Springer Science + Business Media Finance Inc. (SSBM Finance Inc). SSBM Finance Inc is a Delaware corporation.

Dedicated to my idols, Mom and Dad, and my love, Stefanie.

—Mario Zechner

Dedicated to my children and everyone involved in helping make this book happen. Go Sox.

—J.F. DiMarzio

Dedicated to my family and everyone who has helped us along the way.

—Robert Green

Introduction

Hi there, and welcome to the world of Android game development. You came here to learn about game development on Android, and we hope to be the people who enable you to realize your ideas.

Together we’ll cover quite a range of materials and topics: Android basics, audio and graphics programming, a little math and physics, OpenGL ES, an intro to the Android Native Development Kit (NDK), and, finally, publishing, marketing, and making money from your game. Based on all this knowledge, we’ll develop three different games, one of which is even 3D.

Game programming can be easy if you know what you’re doing. Therefore, we’ve tried to present the material in a way that not only gives you helpful code snippets to reuse, but also actually shows you the big picture of game development. Understanding the underlying principles is the key to tackling ever more complex game ideas. You’ll not only be able to write games similar to the ones developed over the course of this book, but you’ll also be equipped with enough knowledge to go to the Web or the bookstore and take on new areas of game development on your own.

Who This Book Is For

This book is aimed first and foremost at complete beginners in game programming. You don’t need any prior knowledge on the subject matter; we’ll walk you through all of the basics. However, we need to assume a little knowledge on your end about Java. If you feel rusty on the matter, we’d suggest refreshing your memory by reading Thinking in Java by Bruce Eckel (Prentice Hall, 2006), an excellent introductory text on the programming language. Other than that, there are no other requirements. No prior exposure to Android or Eclipse is necessary!

This book is also aimed at intermediate-level game programmers who want to get their hands dirty with Android. While some of the material may be old news for you, there are still a lot of tips and hints contained here that should make reading this book worthwhile. Android is a strange beast at times, and this book should be considered your battle guide.

How This Book Is Structured

This book takes an iterative approach in that we’ll slowly but surely work our way from the absolute basics to the esoteric heights of hardware-accelerated game programming goodness. Over the course of the book, we’ll build up a reusable code base that you can use as the foundation for most types of games.

If you’re reading this book purely as a learning exercise, we suggest going through the chapters in sequence, starting from Chapter 1 . Each chapter builds off of the previous chapter, which makes for a good learning experience.

If you’re reading this book with the intent to publish a new game at the end, we highly recommend you skip to Chapter 14 and learn about designing your game to be marketable and make money, then come back to the beginning and begin development.

Of course, more experienced readers can skip certain sections they feel confident with. Just make sure to read through the code listings of sections you skim over so you will understand how the classes and interfaces are used in subsequent, more advanced sections.

Downloading the Code

This book is fully self-contained; all the code necessary to run the examples and games is included. However, copying the listings from the book to Eclipse is error prone, and games do not consist of code alone, but also have assets that you can’t easily copy out of the book. We took great care to ensure that all the listings in this book are error free, but the gremlins are always hard at work.

To make this a smooth ride, you can download the source code and related assets from the Apress website. For more details, see the book’s product page at www.apress.com/9781484204733 . The download file will offer you the following:

  • The complete source code and assets available from the project’s Subversion repository. The code is licensed under the Apache License 2.0 and hence is free to use in commercial and noncommercial projects. The assets are licensed under the Creative Commons BY-SA 3.0. You can use and modify them for your commercial projects, but you have to put your assets under the same license!

For each chapter that contains code, there’s an equivalent Android Studio project. The projects do not depend on each other, as we’ll iteratively improve some of the framework classes over the course of the book. Therefore, each project stands on its own. The code for both Chapters 5 and 6 is contained in the ch06-mrnom project.

Contacting the Authors

Should you have any questions or comments or even spot a mistake you think we should know about you can contact Mario Zechner by registering an account and posting at http://badlogicgames.com/forum/viewforum.php?f=21 , or Robert Green by visiting www.rbgrn.net/contact .

We prefer being contacted through the forums. That way other readers benefit as well, as they can look up already answered questions or contribute to the discussion!

Acknowledgments

I’d like to thank the excellent team at Apress, who made this book possible. Specifically, I’d like to thank Candace English, Adam Heath, Matthew Moodie, Damon Larson, James Compton, Christine Ricketts, Tom Welsh, Bill McManus, and many more good souls who have worked on this book.

Thanks to Robert Green for being a great co-author and for living through the hell of early Android versions with me.

Another big thanks to my splendid team of contributors, who carried on the libgdx effort while I was busy writing this book. I’d especially like to thank my friend Nathan Sweet the months we spent together in San Francisco and Graz were some of the most memorable times in my life; Ruben Garat and Ariel Coppes from Gemserk, who make sure we stay on target with libgdx; Justin Shapcott, who keeps cleaning up my mess in the libgdx repository; Søren Nielsen, one of the most knowledgeable artists I’ve ever had the pleasure to work with, who’s a helping hand in the libgdx IRC channel; and, finally, all the folks on the libgdx IRC channel and the forums, whom I consider to be extended family.

Last but not least, thanks to Mom and Dad for being folks to look up to, and to my love, Stefanie, who put up with all the long nights alone in bed, as well as my grumpiness. Lyrt!

—Mario Zechner

I’d like to thank Mark, Steve, Paul, and the team at Apress for making this book happen. I’d also like to thank Stacey, Katrina, and the agents and team at Studio B for handling the hard part of the process for over 15 years. Finally, I’d like to thank Christian, Sophia, Giovanni, Jennifer, Katie, Sarah, Joseph, and the rest of my family for being patient and understanding throughout.

—J.F. DiMarzio

I’d like to thank Mario for answering so many questions and helping me work through a few tricky bugs over the years. Ryan Foss is an artist and programmer I worked with to build several games and is truly an exceptional person. Scott Lembcke of Howling Moon Software helped me through some difficult programming problems. Zach Wendt, organizer of the Minneapolis IGDA, always hung out late after meetings and talked tech with me. Thanks to Dmitri Salcedo, who’s been sticking with me through a tough year and helping us to achieve more than we ever have before. Finally, I thank all of the original licensees of BatteryTech SDK, who believed in the product before anyone else. Thank you all for your support and help; I couldn’t have made it without you.

—Robert Green

Contents

  1. Chapter 1:​ An Android in Every Home
    1. A Brief History of Android
    2. Fragmentation
    3. The Role of Google
      1. The Android Open Source Project
      2. Google Play
      3. Google I/​O
    4. Android’s Features and Architecture
      1. The Kernel
      2. The Runtime and Dalvik
      3. System Libraries
      4. The Application Framework
    5. The Software Development Kit
    6. The Developer Community
    7. Devices, Devices, Devices!
      1. Hardware
      2. The Range of Devices
    8. Compatibility Across All Devices
    9. Mobile Gaming Is Different
      1. A Gaming Machine in Every Pocket
      2. Always Connected
      3. Casual and Hardcore
      4. Big Market, Small Developers
    10. Summary
  2. Chapter 2:​ First Steps with Android Studio
    1. Setting Up the Development Environment
      1. Setting Up the JDK
      2. Installing Android Studio
      3. Setting Up the Android SDK
      4. A Quick Tour of Android Studio
    2. Creating a New Project in Android Studio and Writing Your Code
      1. Creating the Project
      2. Exploring the Project
      3. Writing the Application Code
    3. Running the Application on a Device or Emulator
      1. Connecting a Device
      2. Creating an Android Virtual Device
      3. Installing Advanced Emulator Features
      4. Running an Application
    4. Debugging and Profiling an Application
      1. LogCat
    5. Summary
  3. Chapter 3:​ Game Development 101
    1. Genres:​ To Each One’s Taste
      1. Casual Games
      2. Puzzle Games
      3. Action and Arcade Games
      4. Tower-Defense Games
      5. Social Games
      6. Beyond the Genres
    2. Game Design:​ The Pen Is Mightier Than the Code
      1. Core Game Mechanics
      2. A Story and an Art Style
      3. Screens and Transitions
    3. Code:​ The Nitty-Gritty Details
      1. Application and Window Management
      2. Input
      3. File I/​O
      4. Audio
      5. Graphics
    4. The Game Framework
    5. The Game and Screen Interfaces
    6. A Simple Example
    7. Frame Rate–Independent Movement
    8. Summary
  4. Chapter 4:​ Android for Game Developers
    1. Defining an Android Application:​ The Manifest File
      1. The <manifest> Element
      2. The <application> Element
      3. The <activity> Element
      4. The <uses-permission> Element
      5. The <uses-feature> Element
      6. Game Project Setup in Six Easy Steps
      7. Google Play Filters
      8. Defining the Icon of Your Game
    2. Android API Basics
      1. Creating a Test Project
      2. The Activity Life Cycle
      3. Input Device Handling
      4. File Handling
      5. Audio Programming
      6. Playing Sound Effects
      7. Streaming Music
      8. Basic Graphics Programming
    3. Best Practices
    4. Summary
  5. Chapter 5:​ An Android Game Development Framework
    1. Plan of Attack
    2. The AndroidFileIO Class
    3. AndroidAudio, AndroidSound, and AndroidMusic:​ Crash, Bang, Boom!
    4. AndroidInput and AccelerometerHan​dler
      1. AccelerometerHan​dler:​ Which Side Is Up?​
    5. CompassHandler
    6. The Pool Class:​ Because Reuse Is Good for You!
    7. KeyboardHandler:​ Up, Up, Down, Down, Left, Right
      1. Touch Handlers
      2. AndroidInput:​ The Great Coordinator
    8. AndroidGraphics and AndroidPixmap:​ Double Rainbow
      1. Handling Different Screen Sizes and Resolutions
      2. AndroidPixmap:​ Pixels for the People
      3. AndroidGraphics:​ Serving Our Drawing Needs
      4. AndroidFastRende​rView:​ Loop, Stretch, Loop, Stretch
    9. AndroidGame:​ Tying Everything Together
    10. Summary
  6. Chapter 6:​ Mr.​ Nom Invades Android
    1. Creating the Assets
    2. Setting Up the Project
      1. MrNomGame:​ The Main Activity
      2. Assets:​ A Convenient Asset Store
      3. Settings:​ Keeping Track of User Choices and High Scores
      4. LoadingScreen:​ Fetching the Assets from Disk
    3. The Main Menu Screen
    4. The HelpScreen Classes
    5. The High-Scores Screen
      1. Rendering Numbers:​ An Excursion
      2. Implementing the Screen
    6. Abstracting the World of Mr.​ Nom:​ Model, View, Controller
      1. The Stain Class
      2. The Snake and SnakePart Classes
      3. The World Class
    7. The GameScreen Class
    8. Summary
  7. Chapter 7:​ OpenGL ES:​ A Gentle Introduction
    1. What Is OpenGL ES and Why Should I Care?​
      1. The Programming Model:​ An Analogy
      2. Projections
      3. Normalized Device Space and the Viewport
      4. Matrices
      5. The Rendering Pipeline
    2. Before We Begin
    3. GLSurfaceView:​ Making Things Easy Since 2008
    4. GLGame:​ Implementing the Game Interface
    5. Look Mom, I Got a Red Triangle!
      1. Defining the Viewport
      2. Defining the Projection Matrix
      3. Specifying Triangles
      4. Putting It Together
    6. Specifying Per-Vertex Color
    7. Texture Mapping:​ Wallpapering Made Easy
      1. Texture Coordinates
      2. Uploading Bitmaps
      3. Texture Filtering
      4. Disposing of Textures
      5. A Helpful Snippet
      6. Enabling Texturing
      7. Putting It Together
      8. A Texture Class
    8. Indexed Vertices:​ Because Re-use Is Good for You
      1. Putting It Together
      2. A Vertices Class
    9. Alpha Blending:​ I Can See Through You
    10. More Primitives:​ Points, Lines, Strips, and Fans
    11. 2D Transformations:​ Fun with the Model-View Matrix
      1. World and Model Space
      2. Matrices Again
      3. An Initial Example Using Translation
      4. More Transformations
    12. Optimizing for Performance
      1. Measuring Frame Rate
      2. What’s Making My OpenGL ES Rendering So Slow?​
      3. Removing Unnecessary State Changes
      4. The Concept of Binding Vertices
      5. In Closing
    13. Summary
  8. Chapter 8:​ 2D Game Programming Tricks
    1. Before We Begin
    2. In the Beginning .​ .​ .​ There Was the Vector
      1. Working with Vectors
      2. A Little Trigonometry
      3. Implementing a Vector Class
      4. A Simple Usage Example
    3. A Little Physics in 2D
      1. Newton and Euler:​ Best Friends Forever
      2. Force and Mass
      3. Playing Around, Theoretically
      4. Playing Around, Practically
    4. Collision Detection and Object Representation in 2D
      1. Bounding Shapes
      2. Constructing Bounding Shapes
      3. Game Object Attributes
      4. Broad-Phase and Narrow-Phase Collision Detection
      5. An Elaborate Example
    5. A Camera in 2D
      1. The Camera2D Class
      2. An Example
    6. Texture Atlas:​ Because Sharing Is Caring
      1. An Example
    7. Texture Regions, Sprites, and Batches:​ Hiding OpenGL ES
      1. The TextureRegion Class
      2. The SpriteBatcher Class
    8. Sprite Animation
      1. The Animation Class
      2. An Example
    9. Summary
  9. Chapter 9:​ Super Jumper:​ A 2D OpenGL ES Game
    1. Core Game Mechanics
    2. Developing a Backstory and Choosing an Art Style
    3. Defining Screens and Transitions
    4. Defining the Game World
    5. Creating the Assets
      1. The UI Elements
      2. Handling Text with Bitmap Fonts
      3. The Game Elements
      4. Texture Atlas to the Rescue
      5. Music and Sound
    6. Implementing Super Jumper
      1. The Assets Class
      2. The Settings Class
      3. The Main Activity
      4. The Font Class
      5. The GLScreen Class
      6. The Main Menu Screen
      7. The Help Screens
      8. The High-Scores Screen
      9. The Simulation Classes
      10. The Game Screen
      11. The WorldRenderer Class
    7. Summary
  10. Chapter 10:​ OpenGL ES:​ Going 3D
    1. Before We Begin
    2. Vertices in 3D
      1. Vertices3:​ Storing 3D Positions
      2. An Example
    3. Perspective Projection:​ The Closer, the Bigger
    4. Z-buffer:​ Bringing Order to Chaos
      1. Fixing the Previous Example
      2. Blending:​ There’s Nothing Behind You
      3. Z-buffer Precision and Z-fighting
    5. Defining 3D Meshes
      1. A Cube:​ Hello World in 3D
      2. An Example
    6. Matrices and Transformations, Again
      1. The Matrix Stack
      2. Hierarchical Systems with the Matrix Stack
      3. A Simple Camera System
    7. Summary
  11. Chapter 11:​ 3D Programming Tricks
    1. Before We Begin
    2. Vectors in 3D
    3. Lighting in OpenGL ES
      1. How Lighting Works
      2. Light Sources
      3. Materials
      4. How OpenGL ES Calculates Lighting:​ Vertex Normals
      5. In Practice
      6. Some Notes on Lighting in OpenGL ES
    4. Mipmapping
    5. Simple Cameras
      1. The First-Person, or Euler, Camera
      2. An Euler Camera Example
      3. A Look-At Camera
    6. Loading Models
      1. The Wavefront OBJ Format
      2. Implementing an OBJ Loader
      3. Using the OBJ Loader
      4. Some Notes on Loading Models
    7. A Little Physics in 3D
    8. Collision Detection and Object Representation in 3D
      1. Bounding Shapes in 3D
      2. Bounding Sphere Overlap Testing
      3. GameObject3D and DynamicGameObjec​t3D
    9. Summary
  12. Chapter 12:​ Android Invaders:​ The Grand Finale
    1. Core Game Mechanics
    2. Developing a Backstory and Choosing an Art Style
    3. Defining Screens and Transitions
    4. Defining the Game World
    5. Creating the Assets
      1. The UI Assets
      2. The Game Assets
      3. Sound and Music
    6. Plan of Attack
    7. The Assets Class
    8. The Settings Class
    9. The Main Activity
    10. The Main Menu Screen
    11. The Settings Screen
    12. The Simulation Classes
      1. The Shield Block Class
      2. The Shot Class
      3. The Ship Class
      4. The Invader Class
      5. The World Class
    13. The GameScreen Class
    14. The WorldRender Class
    15. Optimizations
    16. Summary
  13. Chapter 13:​ Going Native with the NDK
    1. What Is the Android NDK?​
    2. The Java Native Interface
    3. Setting Up the NDK
    4. Setting Up an NDK Android Project
    5. Creating Java Native Methods
    6. Creating the C/​C++ Header and Implementation
    7. Building the Shared Library
    8. Putting It All Together
    9. Summary
  14. Chapter 14:​ Marketing and Monetizing
    1. Monetizing Your Game
    2. Advertising
      1. Ad Providers
      2. Ad Aggregation Services
      3. Game Advertising Tips
    3. In-App Products
    4. Virtual Currency
    5. To Sell or Not to Sell
      1. Licensing
    6. Getting Your Game Discovered
      1. Social Network Integration
      2. Discovery Services
      3. Blogs and Conventional Web Media
    7. Monetizable by Design
    8. Discoverable by Design
    9. Summary
  15. Chapter 15:​ Publishing Your Game
    1. A Word on Testing
    2. Becoming a Registered Developer
    3. Signing Your Game’s APK
    4. Putting Your Game on Google Play
    5. Publish!
    6. More on the Developer Console
    7. Summary
  16. Index

About the Authors and About the Technical Reviewer

About the Authors

A340874_3_En_BookFrontmatter_Figb_HTML.jpg

Mario Zechner has been programming games since age 12. Over the years, he has created many prototypes and finished games on various platforms. He’s the creator of libgdx, an Android game development framework used by many top-grossing Android games. Before he joined his current employer, Mario was the tech-lead at a mobile gaming startup in San Francisco. Mario’s current day job involves working in the fields of information extraction and retrieval, visualization, and machine learning. You can meet Mario at conferences, where he gives talks and workshops on game programming, read his blog at www.badlogicgames.com , or follow him on Twitter @badlogicgames .

J. F. DiMarzio is a seasoned Android developer and author. He began developing games in Basic on the TRS-80 Color Computer II in 1984. Since then, he has worked in the technology departments of companies such as the U.S. Department of Defense and the Walt Disney Company. He has been developing on the Android platform since the beta release of version .03, and he has published two professional applications and one game on the Android Marketplace. DiMarzio is also an accomplished author. Over the last 15 years, he has released 12 books, including Android: A Programmer’s Guide . His books have been translated into four languages and published worldwide. DiMarzio’s writing style is very easy to read and understand, which makes the information in the topics that he presents more retainable.

A340874_3_En_BookFrontmatter_Figc_HTML.jpg

Robert Green is the founder of the game studio Battery Powered Games in Portland, Oregon. He has developed over a dozen Android games, including Deadly Chambers , Antigen , Wixel , Light Racer , and Light Racer 3D . Before diving full time into mobile video game development and publishing, Robert worked for software companies in Minneapolis and Chicago, including IBM Interactive. Robert’s current focus is cross-platform game development and high-performance mobile gaming with the BatteryTech SDK. Robert often updates his personal blog with game programming tidbits at www.rbgrn.net . You can check out his professional game development software at www.batterypoweredgames.com .

About the Technical Reviewer

A340874_3_En_BookFrontmatter_Figd_HTML.jpg

Paul Trebilcox-Ruiz is a software engineer at Sphero (they make awesome robots that you can control from your phone) in Boulder, Colorado, and a computer science graduate from California State University, Fresno. His main interests lie in the Android platform, Android TV, and wearable computing. He also actively participates in hackathons in the Denver Boulder area, writes an Android technical blog, and presents to Meetups in the area.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset