35,99 €
If you are an intermediate-level Android developer who wants to create highly interactive and amazing games with the Android SDK, then this book is for you.
Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:
Seitenzahl: 390
Veröffentlichungsjahr: 2015
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-78355-177-4
www.packtpub.com
Author
Raul Portales
Reviewers
Sergio Viudes Carbonell
Antonio Hernández Niñirola
Commissioning Editor
Nadeem N. Bagban
Acquisition Editor
Harsha Bharwani
Content Development Editor
Arun Nadar
Technical Editor
Ruchi Desai
Copy Editors
Stephen Copestake
Akshata Lobo
Project Coordinator
Nikhil Nair
Proofreader
Safis Editing
Indexer
Monica Ajmera Mehta
Graphics
Abhinash Sahu
Production Coordinator
Conidon Miranda
Cover Work
Conidon Miranda
Raul Portales is a software engineer who works as a contract consultant with Platty Soft. He cofounded the game studio The Pill Tree, which ran for a year and produced several titles that were featured by Google Play, including Chalk Ball and SpaceCat.
He has been a Google Developer Expert for Android since the start of 2015, and he loves public speaking. He has presented at several DroidCons and Game Developers conferences, talking about how to survive as an indie game developer.
At the moment, Raul lives in Dublin and you can easily find him collaborating with the local community on different meetups, especially the ones organized by GDG Dublin.
Sergio Viudes Carbonell is a 32-year-old developer from Elche (Spain). He has loved to play video games since his childhood days (since the ZX Spectrum was around). Also, he has drawn and composed electronic music as a hobby. Then, he started coding and studied computer engineering at the University of Alicante.
He started working as a software and web developer. But he always wanted to create video games. So, he founded Baviux and now Sergio, designing and developing mobile apps and games. He has reviewed the following books for Packt Publishing in the past:
I would like to thank Raul Portales for writing this book. Special thanks go to my wife, Estefanía, who encourages and supports me every day.
Antonio Hernández Niñirola is a European PhD candidate in software engineering in the last phase of his doctorate program. He has a BSc in computer science and a masters degree by the University of Murcia in Spain.
Currently located in San Francisco since May 2015, he is working as part of the Android development team at Yelp.
In the academic year 2013-14, he worked with the Department of Software Engineering in the Université Mohammed V in Rabat. This was a great opportunity to focus on his research on mobile usability and resulted in several academic papers for both JCR journals and CORE conferences.
He has also collaborated with Packt Publishing in the past as both author and reviewer. If you want to learn more advanced techniques on testing and security for Android, check out his book Testing and Securing Android Studio Applications, also published by Packt Publishing. If you are new to Android development, you can check these books he has reviewed: Android Studio Application Development and Android Studio Essentials.
For more information on him, visit his website (http://www.ninirola.es) and follow him on Twitter at @hdezninirola.
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 <[email protected]> for more details.
At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters and receive exclusive discounts and offers on Packt books and eBooks.
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.
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.
All your android are belong to us.
Android is the most widespread Operating System and games are what people spend most time using on their phones. Video games have never been easier to make and distribute. Who would not want to make games for Android?
And on top of this, making games is fun!
You will build a real-time game from scratch using the Android SDK. Starting with the creation of a game engine and moving into handling user input, doing efficient drawing, implementing collision detection, playing sound effects, using animations, and so on. You will learn all the aspects of developing a game using a space shooter game as the example that will evolve with you throughout the chapters.
Chapter 1, Setting Up the Project, allows you to set up the project and will describe in which cases it makes sense to use the Android SDK for a game and in which cases it is best to use an external engine. We will create the top-level architecture of a game engine and study how it is different from the one of a typical app, explaining why there is an update thread and why it is separated from the input thread and also from the draw thread.
Chapter 2, Managing User Input, discusses how to read and process user input and how to make controls for our game, from making a virtual gamepad to evolving it as a virtual joystick to adding support for physical controllers. Finally, we'll introduce how to use sensors as input.
Chapter 3, Into the Draw Thread, explores how drawing on a canvas provides better performance. We will discuss the pros and cons of using a normal view versus a SurfaceView.
Chapter 4, Collision Detection, explains how to run and add a basic collision detection system to our game and shows how it fits inside the game engine.
Chapter 5, Particle Systems, helps us learn several uses of particle systems and we'll build one based on the Leonids library wherein a particle system is a big part of a game.
Chapter 6, Sound FX and Music, explores the different options to play sound effects and music in Android and we'll build a SoundManager to handle them since a game feels incomplete without sounds.
Chapter 7, Menus and Dialogs, explains techniques to use the same layouts across phones and tablets and learn how to make them work on both because a compelling UI requires nice menus and dialogs. Finally, since the dialogs available in the Android framework are quite limited, we'll see how we can create more complex dialogs.
Chapter 8, The Animation Framework, dives into the different ways Android offers to animate views and objects and what they can be used for, from frame-by-frame animations to view animations and property animators.
Chapter 9, Integrating Google Play Services, covers the tools that Google Play Services offers for game developers. We'll see the integration of achievements and leaderboards in detail, take an overview of events and quests, save games, and use turn-based and real-time multiplaying.
Chapter 10, To the Big Screen, explores the extra restrictions that games have when going to Android TV, mainly screen overcast and controller-based navigation and also extra options in the Manifest that are specific for Android TV.
Appendix, API Levels for Android Versions, lists all 22 API levels, from Base to Lollipop_MR1, along with the version code.
For this book, you will need the latest version of Android Studio and the Android SDK for Lollipop or newer (API level 22) versions, which you can download using Android Studio.
Android Studio is a free tool that you can download from https://developer.android.com/sdk/index.html and it runs on Windows, Mac, and Linux.
It is advisable to have several Android devices for testing, but is not necessary. It is also advisable to have a Bluetooth game controller (which will become useful for any mobile game developer anyway), but it is not required.
If you are an Android developer who wants to make games and doesn't want to learn a new third-party tool or engine, this book is for you. Make the journey of building a game from scratch to get insights into all the aspects of game development, from implementing your own engine to getting a game ready for Android TV, always with a hands-on approach.
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: "It will be used intensively during onUpdate and onDraw."
A block of code is set as follows:
When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:
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: "We have a link at the bottom named Get resources that pops up a dialog with the string resources we need."
Warnings or important notes appear in a box like this.
Tips and tricks appear like this.
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.
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.
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.
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/1774OS_ImageBundle.pdf.
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 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.
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.
In this chapter, we will describe the situations in which it makes sense to use the Android SDK for a game and those where it is best to use an external engine, explaining the pros and cons of each case.
We will create a simple project that we will be improving throughout the book, until it becomes a complete game. The particular game we are going to build is a Space Shooter.
A few top-level decisions will be made and explained, such as which orientation to use and how are we going to use activities and fragments.
We will describe the top-level architecture of a game engine, study how it is different from a typical app's, explaining why there is an UpdateThread and how it interacts with the user input and why it is separated from the DrawThread; we will include those elements in our project.
Once the game engine is completed, we will expand the project to show a pause dialog, handle the Android back key properly, be consistent with the Activity lifecycle, and make it fullscreen.
Finally, we will summarize some best practices in writing code for games.
Topics that will be covered in this chapter are as follows:
Before we begin entering the details about making games with the Android SDK, let's first take a step back and consider why are we doing this and what the other alternatives are for making a game that runs on Android.
People tend to reinvent the wheel quite often and developers use to do it ever more, especially in the case of video games. While creating a complete engine from scratch is a great learning experience, it also takes a lot of time. So, if you want to just make a game, it may be more cost-efficient for you to use one of the existing engines instead.
We are in a golden age of tools for creating video games. Not only are there lots of them, but most of them are free as well. This makes choosing the right one a little bit more complicated.
Let's take a look at several questions to help us decide which tool to use to suit the needs of a specific game. Since you are already reading this book, I consider that multiplatform is not high on your list of priorities and that reusing your existing Java and Android knowledge is a plus.
If the answer is yes; I would definitely recommend you to use an already existing engine. There are some well-known tasks you'll need to implement to build even the simplest 3D engine such as loading models, loading and applying textures, handling transformations, and dealing with cameras. On top of this, you'd need to be writing OpenGL. All this is a lot of work.
Writing an OpenGL engine is the very definition of reinventing the wheel. It is fine if what you want is to learn the internals of a 3D engine, but if you go this road you'll spend a few months before you can even start with the game. If you want to go straight into making the game, you'd better start with an existing 3D engine.
The second question on this road is: do you prefer to work with code or are you more comfortable with a complete editor? For code, you can use jPCT-AE and libGDX, while, on the editor side, the most common alternative is Unity.
An affirmative answer to this question should point you straight to an existing engine.
Physics simulation is a very well-known area where there is a lot of documentation, and you should be able to implement your own physics engine. Again, this is a great learning experience, but if you want to go straight into making the game it is much more convenient to use an existing engine that supports physics. The most used physics engine around is Box2D, which is written in C++ and it has been ported to Android using the NDK.
While we are going to talk about collision detection later in the book, physics is out beyond the scope of this book. Anything more complex than two spheres colliding can become quite complex to handle.
Once again, it depends whether you prefer to work with code or if you want a complete editor. To work with code, AndEngine should be your weapon of choice. In the case of an editor, Corona and Unity are among the most popular choices.
Most of the feature-rich environments we are mentioning have their own environment, including a specific IDE. It takes effort to learn them and some of them use a different language (for example Unity has its own environment and uses JavaScript or C#).
On the other hand, the frameworks are simpler. You just have to include them and you'll still be writing an Android game. This is an interesting middle ground, where you still can reuse your Android and Java knowledge and make use of features such as physics or 3D models. In this section, we can mention AndEngine for 2D and physics and jPCT-AE for 3D as good options.
There are several advantages to building games using the Android SDK:
Of course, not everything is awesome. There are some serious disadvantages, most of them already mentioned, such as:
Are you still here? Congratulations, you have chosen the right book!
If you want to explore other options, there are books available for Unity, AndEngine, and libGDX, and published by Packt.
Now that we are all on the same page, let's get down to business.
Along the book, we will be building a game as a demo of the concepts we will be studying in each chapter. The game is going to be a classic Space Shooter arcade game. We'll call it YASS—Yet Another Space Shooter.
This means some decisions will be taken for this particular type of game, but other options will also be commented since the book is meant for generic video game development.
We are going to create a project with a single Activity and we will add fragments when necessary.
In the versions prior to Android 5.0 Lollipop, the transitions between activities could be modified, but only in a very limited way. The user can even disable them in a setting. All in all, this will make your game look clunky while transitioning from one Activity to another. You will need to save the state of the Activity in case it gets destroyed. Since each Activity is a separate instance, you will need to take care of communication among them, if required.
On the other hand, when you work with fragments, you never exit the Activity and you have complete control over the transition animations. In addition to these, you still have the code and layout of each section separated, so modularity and encapsulation are not compromised.
Finally, when it comes to handling third-party libraries such as In-App Billing or Google Play services, you have to take care if initialization and configuration only once, since those are linked at the Activity level.
For games, it is more efficient to use only one Activity with multiple Fragments.
One good practice is to have a base Fragment for our game (YassBaseFragment) from which all the other fragments will inherit. One good use of this fragment is to have a method to replace getActivity that returns our specific Activity, but there are other cases in which having a common base fragment is handy.
We are going to use Android Studio as the IDE. We are going to create the project with minSDK 15 (Ice Cream Sandwich—ICS). As a good practice, we don't want to move the minimum SDK, unless we are using some features that were not available before. By keeping the minSDK low, you make your game available to as many devices as possible.
The two main features we are going to use from ICS are Fragments, ValueAnimators, and ViewPropertyAnimators. All of these were already available in Honeycomb, but 3.x is considered little more than a test for ICS; it was not mature and has been replaced by ICS in almost all devices.
In the unlikely case that you want to support older versions such as Gingerbread, you can make use of the compatibility library and NineOldAndroids to add backwards-compatibility for the features we are using.
Let's go on and navigate to File > New Project. We are going to use YASS as the Application name and example.com as the Company Domain.
We include support for Android TV, since we want to be able to run our game on the big screen. This will create an extra module that we can compile for, but we are not going to touch this until the last chapter.
As explained before, we will use Minimum SDK version 15 for phones and 21 for Android TV, since this is when it was made available.
For the Package name of the application, we are going to use com.example.yass.
We are not going to use any of the default wizards, since all of them include the action bar/toolbar that is great for apps, but of no use for games. So, we'll go with the empty project options:
Similarly, we are not going to create any Activity for TV:
Once the project is created, we will create a single Activity with one Fragment. This is done via the menu option New > Activity > Blank Activity with Fragment.
We are going to customize the Activity by filling the dialog as follows:
This will create the following files:
Since we did not tell Android Studio that this activity is going to be our launch activity, we need to edit the AndroidManifest.xml to configure it as such, by adding the proper intent filter:
We are not going to use menus at all, so there are a few methods and files we will not need and we can delete them. You can leave all those methods there if you want, but it is better to have a clean environment, free of unused code.
So, we can remove the menu folder under resources and the files in it, which are meant to be the menu for the YassActivity.
The methods that handle menu-creation and menu-item-selection are also useless, so we can remove the following methods from YassActivity:
Deciding the orientation of a game is a very important point. Given the diversity of Android phones, the resolution and aspect ratio are a couple of things we have to deal with.
Gaming is traditionally done in landscape orientation: computers have monitors in landscape mode, and so do TV screens when you play with your gaming console. Almost all handheld consoles are designed with landscape orientation as well. Even more, most tablets consider landscape to be the default orientation.
Landscape is the traditional orientation for gaming.
YASS is going to be a landscape game. The key reason why we are doing it is to be able to port the game to Android consoles later on, both on Android TV and OUYA. This does not mean that the portrait mode is not a valid orientation for games, but it is a less familiar one for players.
We are going to use sensorLandscape instead of just landscape, so the device can rotate 180 degrees to adjust to whatever side is down. We have to update the AndroidManifest.xml to look like this:
As you probably know, when an Activity changes orientation on Android, it is destroyed and recreated and so are all the fragments inside it. This means that, unless you explicitly save and restore information, the fragments will not remember the previous state.
The sensorLandscape and sensorPortrait modes do not destroy activities on rotation.
Some good news here: while using sensorLandscape, the rotation does not kill the Activity, so no extra work is required. This happens because the layout is exactly the same and nothing needs to be recreated.
If you plan to make a game that can rotate, you must pay extra attention to saving and restoring the status of the game when the orientation changes. This in itself is another good reason to keep the game locked to a particular orientation, be it landscape or portrait.
Android devices come in a lot of different aspect ratios, form 4:3 to 16:9 at least. This is not counting the number of pixels.
While designing a game for multiple aspect ratios, there are basically two ways of doing it. For each of them, we design for the most extreme aspect ratio. We will be using the extra space for "smart letterboxes," which means that we can have more game view.
Several ways of designing for different aspect ratios
The most common option is to make the camera centered and fix the smallest size (the height for the landscape orientation). This allows for more view space on the sides, while making sure that the smallest screen will have enough display space. This is the equivalent of viewing 4:3 images on a 16:9 screen.
You can also fix the bigger size if the game design makes sense. This will add extra space on the top and bottom if the screen is square. This is the equivalent of viewing 16:9 images on a 4:3 screen.
There is an alternative approach: simply having "more camera space." We can, as well, make the game view a certain size and use the extra space for other controls such as scores, levels, and so on.
If you take this approach to the extreme, you can design the game area completely square and put the extra information in "smart letterboxes" for both landscape and portrait. One very good example of this approach is done by Candy Crush Saga. This is the best approach for versatility, but it is also the one that requires the most work.
For our game, we are going to use a "more camera space" approach with fixed size letterboxes to display scores and lives.
For the difference in resolution and pixel density, we will be designing for a low density screen. We will read the resolution of the device programmatically and apply a conversion factor. Some in-depth details of this approach are given in the chapters dedicated to low-level drawing, menus, and dialogs.