Getting Started in Android Game Development

If you're interested in developing a game for the Android platform, there is a lot you need to know.  I'm the developer of Light Racer, Light Racer 3D, Antigen, Deadly Chambers and Wixel, which are currently available on the Android Market. I've also been involved with the development of about 5 other games for Android and iOS and am co-author of Beginning Android Games 2nd Edition.  I've developed games before but the original Light Racer was my first Android application and I learned quite a bit about writing Android games that I'd like to share with everyone.  I even wrote an online book detailing the development of Light Racer 3D, which is full of how-tos and useful code snippets. If you have previous experience with game development, moving over to the mobile platform won't be all that difficult.  You will mostly just need to learn the architecture and API.  If you're new to game development, I have assembled a list of must-knows for getting started.  They apply to many different types of games, including action, strategy, simulation and puzzle.

Android is a Java-based environment.  This is nice for new developers as Java is widely accepted as a much easier language to get started in than C++, which is the norm for mobile development and is what I use now.  Google has also done an excellent job with documenting the API and providing examples to use.  There is an example to show functionality for almost 100% of the API, called API Demos.  If you're familiar with Java and have already used Eclipse, getting your first app working should be fairly simple.  If you've never coded anything in your life before, you will have a lot to absorb as you move forward, but don't get discouraged. If you have some experience and are wanting to develop a cross-platform game or high-performance Android game in C++, check out BatteryTech, which is a platform I wrote and am currently using for game development.

Get the SDK

The first step in getting started with the Android platform is to get the Android SDK (Software Development Kit).  The SDK has the core libraries, an emulator, tools and sample code.  I highly recommend using Eclipse and the android eclipse plugin.  Eclipse IDE for Java Developers is fine if you are just doing Android.  If this is your first Java development project, you will want to download the full Java SE Development Kit (JDK) as it contains tools you will need for signing and deploying your application.

Learn the application architecture

As tempting as it may seem to just dive right in, it's very important to understand the android application architecture.  If you don't learn it, you may design things in such a way that will make it very difficult to fix problems with your game down the line.  You will want to understand Applications, Activities, Intents and how they are all related to each other.  Google has provided good information on the architecture here.  The really important thing is to understand why your game may need to consist of more than one Activity and what that means to designing a game with good user experience.  This is where things tie in to the Activity lifecycle.

Learn the activity lifecycle

The activity lifecycle is managed by the Android OS.  Your activity will be created, resumed, paused and destroyed as the OS dictates.  Handling these events correctly is very important to having an application that behaves well and does what the user perceives as correct.  It's very good to know how all of this works before you start designing your game because you will save yourself debugging time and costly redesign time later on.  For most applications, the default settings will work but for games, you may want to consider turning the SingleInstance flag on.  When set as default, android will create new instances of the activity as it sees fit.  For a game, you may only want to have 1 instance of the game activity.  This has some implications for how you need to manage the state of things but for me it solved some resource management issues and it should be considered.

The main loop

Depending on what type of game you are writing, you may or may not have a main loop.  If your game is not time-dependent or if it only responds to what the user does and will wait forever for user input without making any kind of visual changes, you may not need a main loop.  If you are writing an action game or a game that has animations, timers or any kind of automation, you should seriously consider using a main loop.

The main loop of a game is the part that "ticks" sub systems in a specific order and usually as many times per second as possible.  Your main loop will need to run on its own thread.  The reason for this is that Android has a main UI thread and if you don't run your own thread, the UI thread will be blocked by your game which will cause the Android OS to not be able to handle any of its normal update tasks. The order of execution is usually as follows:  State, Input, AI, Physics, Animation, Sound and Video. 

Updating State means to manage state transitions, such as a game over, character select or next level.  Often times you will want to wait a few seconds on a state and the State management is the part that should handle this delay and setting the next state after the time has passed.

Input is any key, scroll or touch from the user.  It's important to handle this before processing Physics because often times input will affect the physics so processing input first will make the game more responsive.  In Android, the input events come in from the main UI thread and so you must code to buffer the input so that your main loop can pick it up when the time comes.  This is not a difficult task.  Defining a field for the next user input and having the onKeyPressed or onTouchEvent set the next user action into that field is all that will be required.  All the Input update needs to do at that point is determine if it is valid input given the state of the game and let the Physics side handle responding to it. 

The AI update is analagous to a user deciding what they are going to "press" next.  Learning how to write AI is out of the scope of this article but the general idea is that the AI will press buttons just like the user does.  This will also be picked up and responded to by the Physics update.

The Physics update may or may not be actual physics.  For action games, the point of it is to take into account the last time it was updated, the current time it is being updated at, the user input and the AI input and determine where everything needs to be and whether any collisions have occured.  For a game where you visually grab pieces and slide them around, it will be the part that is sliding the piece or letting it drop into place.  For a trivia game, it would be the part deciding if the answer is right or wrong.  You may name yours something else, but every game has a part that is the red meat of the game engine and for this article, I'm referring to it as Physics.

Animations aren't as simple as just putting an animated gif into your game.  You will need to have the game draw each frame at the right time.  It's not as difficult as it sounds.  Keeping state fields like isDancing, danceFrame and lastDanceFrameTime allows for the Animation update to determine if its time to switch to the next frame.  That's all the animation update really does.  Actually displaying the change of animation is handled by the video update.
 
The Sound update handles triggering sounds, stopping sounds, changing volumes and changing the pitch of sounds.  Normally when writing a game, the sound update would actually produce a stream of bytes to be delivered to the sound buffer but Android manages its own sounds so your options for games are to use SoundPool or MediaPlayer.  They are both a little sensitive but know that because of some low level implementation details, small, low bitrate OGGs will yield the best performance results and the best stability.

The Video update takes into account the state of the game, the positions of players, scores, statuses, etc and draws everything to screen.  If using a main loop, you will want to use the SurfaceView and do a "push" draw.  With other views, the view itself will call the draw operation and the main loop won't have to do it.  SurfaceView gives the highest frames per second and is the most appropriate for games with animation or moving parts on screen.  All the video update should do is take the state of the game and draw it for this instance in time.  Any other automation is better handled by a different update task.

What's this code look like?  Here's an example.

public void run() {
    while (isRunning) {
        while (isPaused && isRunning) {
            sleep(100);
        }
        update();
    }
}

private void update() {
    updateState();
    updateInput();
    updateAI();
    updatePhysics();
    updateAnimations();
    updateSound();
    updateVideo();
}


3D or 2D?

Before you start on your game, you need to decide if you're going to go 3D or 2D.  2D games have a much lower learning curve and generally are easier to get good performance on.  3D games require much more in-depth math skills and may have performance issues if you are not very careful.  They also require the ability to use modeling tools like 3D Studio and Maya if you intend to have shapes more complex than Boxes and Circles.  Android supports OpenGL for 3D programming and there are many good tutorials on OpenGL that one can find to learn it.

Build simple, high quality methods

When getting started, make sure that you avoid writing one big long monolithic method that is "the game."  If you follow the main loop pattern that I described above, this should be fairly easy.  Each method you write should accomplish one very specific task and it should do so error-free.  For example, if you need to shuffle a deck of cards, you should have a method called "shuffleCards" and that should be all it does. 

This is a coding practice that applies to all software development but it's particularly important in game development.  Debugging can get very difficult in a stateful, real-time system.  Keep your methods small and the general rule of thumb is that each method should have 1 and only 1 purpose.  If you're going to programatically draw a background for a scene, you may want a method called "drawBackground."  Things like that will make it so that you develop your game in terms of building blocks and you will continue to be able to add what you need without making it too complex to understand.
 
It's all about efficiency!

Performance is a major issue for any game.  The goal is to make the game as responsive as possible and to also look as smooth as possible.  Certain methods like Canvas.drawLine are going to be slow.  Also drawing an entire screen-sized bitmap onto the main canvas every frame will also be costly.  Balancing things like that is necessary to achieve the best performance.  Make sure to manage your resources well and use tricks to use the least amount of CPU to achieve your task.  Even the best game will not be very fun if it can't perform well.  People in general have little tolerance for choppiness or poor response.

Tips and Tricks

Take a look at the example for LunarLander in the SDK.  It uses a SurfaceView and that would be the appropriate view to use for a game that needs the highest number of frames per second possible.  If you're going 3D, take a look at GLSurfaceView. It takes care of the OpenGL device initialization and provides a mechanism for rendering.  For LightRacer, I had to optimize the way I have everything drawn or else the framerate would be drastically lower.  I drew the background to a Bitmap only once which was when the view is initialized.  The light trails are in their own bitmap which gets updated as the racers move.  Those two bitmaps are drawn to the main canvas every frame with the racers drawn on top and then finally an explosion.  This technique made the game run at a playable rate.

It's also a good practice to have your bitmaps be the exact size you intend to draw them on screen, if applicable.  This makes it so that no scaling is needed and will save some CPU.

Use a consistent Bitmap Configuration (like RGBA8888) throughout the game.  This will save the graphics library CPU in having to translate the different formats.

If you're determined to develop a 3D game but have no 3D knowledge, you will want to pick up a book or two on 3D game programming and study up on linear algebra.  At a bare minimum, you must understand dot products, cross products, vectors, unit vectors, normals, matrixes and translation.  The best book I have come across for this math is called Mathematics for 3D Game Programming and Computer Graphics.

Keep the sound small and at a low bitrate.  The less there is to load, the faster loading times will be and the less memory the game will use.

Use OGGs for sound, PNGs for graphics.

Make sure to release all media players and null out all of your resources when the activity is destroyed.  This will ensure that the garbage collector gets to everything and that you don't have any memory leaks between launches of the game.

Join the Android Google group and find community support.  There will be people that can help you along the way.

Above all, spend time testing and retesting and making sure that every little thing works exactly the way you would expect it to.  Polishing the game up is the longest and hardest part of development.  If you rush it out to market, you will probably have a disappointed crowd and you may feel that all your hard work is wasted.  It's not possible to have 100% of people love what you write but you should at least try to put out the highest quality work that you can.

Google has excellent documentation for getting started here.

Find working game code samples and how-tos in the Light Racer 3D Development Journal

Need a book recommendation? Try Beginning Android Games 2nd Edition by Mario Zechner and Myself (Author of libgdx and friend of mine).

Finally, Battery Powered Games offers pro Android (and iOS) game development consulting services so if your company has a need to contract out mobile game development, that's the place to go!

160 Comments

Post a comment here or discuss this and other topics in the forums

SVG or Vector Graphics Support Questionnaire

I just want to know if Android supports SVG artwork. If not, then can i code the support in my game? And if anyone can kindly help point me in the right direction. Also i find this discussion particularly useful.I would like to thank all of you for the great discussions. Keep it up guys.

I do not think SDL is what

I do not think SDL is what you want nor do I believe it can build for Android ATM. Consider starting from scratch, just experimenting with some basic OpenGL ES drawing and learn how to render the bits and pieces you need.

Will the SDK be enough?

I wish to make a game similar to your "Antigen" and wonder if I need to use the SDL/OpenGL for that?
I have tried to figure out how to get openGL/SDL set up for either windows or Linux (i use andLinux in windows) but I find very poorly documented "how to" for the set up.

If I must (or should) use openGL/SDL for gamedev for the android (2.0 and up) where can I find a proper set-up guide from scratch (that tell me what stuff I need and where to find them and how to set them up) or is there any book on the market that hobby game devs can buy to use the openGL/SDL?

General programming, CS and

General programming, CS and Java specifically.

What education/class?

Hi Robert

I would like to know the answer to this question too.

What kind of education is best suited to program apps?

Thanks

Lots of Questions

Answered! Thank you for answering the ogg and png as best performing. I could not find a clear answer. I found your link when I was looking up wait time before starting code. Great tips... bookmarked.

Thanks

This is so helpful !

Thanks so much.

the info was very helpful thank you very much

the info was very helpful thank you very much

can you tell me what class i should take if i want to learn how to create apps for android and all the graphics and all the other stuff thats related to app making.
thank you very much
please answer, would really appreciate it.

For a lot of games, you can

For a lot of games, you can actually check all of the objects against each other using a very cheap check with an approximation (distance squared on 2 circles). It works like this:

each object needs to have a field that is its size squared, so
object.radius2 = object.radius * object.radius
where radius is a close approximation of how long the radius of a circle would have be from the object center to surround the entire object
the idea is that we're going to put everything into circles and check the distance from one circle center to another comparing their radii for intersection (the cheapest test there is) which is dist = sqrt(d1^2 + d2^2) but we don't want to use sqrt so we're going to simply take it out, which makes distances squared, and we can compare that to our squared radii (object.radius2) since it's all the same :)

for each object o1:
for each object o2:
if not self:
if ((o2.x-o1.x) * (o2.x-o1.x) + (o2.y-o1.y) * (o2.y-o1.y) < o1.radius2 + o2.radius2):
// circle intersection! now do the more complex box check for an accurate check. if that passes, you have a real intersection and should respond.

This will work but since it's exponential you'll start to have problems maybe around 100 objects or so on first gen phones. Like anything, I'd profile it to see what kind of performance you get. There are no divides and no sqrt calls there so it's about as fast as you can do it.

The next thing to do is more complicated and that is to partition the space. You can either use a grid or a quadtree for 2D. Either will work. The idea is that when an object moves, it figures out which cells it occupies in the grid and puts a reference to itself in those cells, removing itself from any other cells. Then when you check for collisions, you go object by object, but you only check other objects in any of the cells that your object is currently in. You will still want to do the sphere check first since that usually does save cycles, especially if you detail check is for shapes other than rectangles.

My problem is not checking

My problem is not checking the intersection, it is determining which moving elements on the screen are close to each other in order to check if they intersect, otherwise I would have to check collision on all collideible elements in the game on each frame.

Thanks! The short answer is:

Thanks!

The short answer is: It depends on the game. Often times it's not just detection you want but a proper response. Very simple games can get away with simple rectangle and sphere intersection tests but many will want some math to determine the angles of collision and slide or bounce as necessary, etc.

Often times your core collision checks do come down to simply checking to see if two rectangles or spheres or combinations have collided but in many cases you will want them to be swept tests to ensure that in an extreme framerate drop, you didn't miss anything.

It's not that hard once you learn it. Just get a book on game math or game collisions.

What About Collision Detection

I found your article and the continued discussion very interesting and helpful.

I'm wondering how do you implement Collision Detection on a 2D game?

I'm using a "QuadList" implementation which I wrote, but I'm running into memory management problems as the list grows too big. Before I go into the depth of this algorithmic world, I'm wondering how others are doing it?

Any insight could be helpful, thnx

Scot, When working by

Scot,

When working by yourself, you will need to be a jack of all trades, and that includes buying and learning to use tools like photoshop, audacity, etc.

I would recommend partnering with someone who knows how to make high quality art but it's equally as important for you to learn how to use it as you'll be the point man for understanding the technical integration of art and game.

Art

I am a developer working on my first Android game. I am creating a basic card game. The thing that I am having the most trouble with is getting images and sound effects to support the game. I am by no means an artist. Do you have any suggestions or recommendations on where I can look to get some basic sound effects and images? Should I be looking for an artist partner? Thank you!

Start simple. For android -

Start simple. For android - just create a surface view. Get a few graphics to draw in it. Get input handling working and just start by logging it to see that it's working. Then try having something happen when you touch somewhere. Learning organically like this is a great way to really understand a system. Add one thing at a time until you have something doing what you want :)

Once you get better with it, take a step back and redesign using your knowledge.

i am so lost

i want to create games i know it takes time and i have downloaded the sdk and eclipse and java sdk
but i am still lost i was trying to find some game examples. i love rpgs and i want to make them for the android phone but i know i need to start easily i need help but i dont know were to start if i could ask can you send me some more info please if you have time i know you must be busy especially having more than one game out on the market

i am just in 1 week going to be starting game creation classes at itt-collage i am so excited but i want to do other easy things as i start school so i have more of an idea of whats going on before the net two years are up that way i have a deeper understanding of whats going on before i get into being lost lol

thank you for your time

Which main loop are you

Which main loop are you referring to? The only delay I illustrated here was during pause while waiting to get out of pause. Normally I recommend sleeping only exactly the amount to cap the update rate, which is the difference between the time used and time remaining.

Great article.

An excellent write-up, thank you very much, got a great deal out of it.

I notice the main loop illustrated only sets a minimum wait period and assumes every frame drawn will take the exact same amount of time which might result in a varying frame rate.

|---------------------- desired frame rate --------------------|
|------ draw time varies -----||----- sleep fixed interval------|
vs.
|---------------------- desired frame rate --------------------|
|------ draw time varies -----||----- sleep time left -------|

Hi Kenneth, It's probably

Hi Kenneth,

It's probably better if you ask them in the forum so others can learn from them as well.

Help me?

could you email me if i gave you my emaIL? i have tons of questions... please and thank you.

You always have to draw your

You always have to draw your layers every frame. What I was saying is that I pre-rendered a background to a bitmap just once instead of recreating it on the surface every frame. I had a dynamic background which consisted of a grid and then some walls that would change every frame. Instead of drawing the background grid and then the walls as another pass on top, I simply updated the single background composite with the little bit of wall change and then drew the composite to the surface, so the surface only had one draw instead of 2.

SurfaceView drawing Background only once

Hello,

Great article!

One question: How did you manage drawing the Background bitmap only once using SurfaceView? I draw the background every frame...

Thanks!

Cool! Nice work. I like

Cool! Nice work. I like that you blogged about the process, too. :)

Android game programming

Hi,

Thanks for providing insight into how to implement the game or main loop... I took your advice and built my first Android 'game' (Conway's Game of Life for Google Android: http://www.quesucede.com/page/show/id/conway_game_of_life_android).

Brett

What most people do is use

What most people do is use variable time updates, so the update is for a duration of time. All you need to do is keep track of the last update time and subtract it from the current time, so you call update(delta) and typically it is like update(33). Your physics use that number to know how much to move, usually by multiplying a movement rate by that number over 1000.

Main Loop

How do i make the main loop adjust according to variable frame rate. The physics update should give different results for 30fps and 50fps. So how do i detect how much time has passed and if something is taking too long how do i prevent(skip) it.

You are correct. In my

You are correct. In my experience, the way to get speed is to reduce the execution overhead which includes things such as method calls, virtual lookups, allocation, etc. It's the sort of stuff that makes Martin Fowler cry but when it comes to games, performance is king.

Don't apply it across the board, though, just in your most-used code (anything in your main loop that runs as fast as possible). Sometimes if you go overboard, you'll find it hard to add features in. There's a balance.

Thanks................

this article has made it quite clear to me that whilst I will always download and play these work shy applications, I will never have the wherewithall to write one myself.

Cheers, you've saved me a load of valuable time.

Walter.

Game Loop

I partially disagree with the comments about creating lots of quality methods. Function calls are expensive and with games and even live wallpapers framerate is key. I wrote a couple graphics based live wallpapers on the android market with the android 2d graphics library and i really struggled with framerate until i completely threw out everything i learned in all my Computer Science classes. Here's some things i learned from continuously trying to improve my live wallpapers.

1. If you use objects dont use getters/setters. Make all your member variables public. Function calls are too expensive and in game loops those functions will get called a ton. It's simple math.
2. Declare as much memory as possible up front. That means all possible game objects/bitmaps, etc... The Android java garbage collector is a huge time waster and will kill you're frame rate!
3. Dont use anything in the Collections namespace if you can avoid it. Stick to arrays.
4. In my "main loop" i actually chose to make the drawing and physics updates on seperate threads since in my case they werent dependent on each other. The drawing is just responsible for drawing a list of objects. The physics thread just responsible for updating the physics of the objects on the screen.

There are those who will probably hate me for saying these things, but it really helped me performance-wise. I think you just have to balance good programming practices with the fact that no one will play laggy games.

There is a great video on the android dev website from a game developer (the guy who wrote replica island) who spoke at google i/o who speaks on this topic as well. It's worth checking out.

Thanks for that

Thanks for that Robert.

Faisal