AndEngine Simple Android Game Tutorial

WARNING: This is an outdated tutorial for the old AndEngine GLES1.0, if you want a tutorial for the new GLES2.0 then Check my Jimvaders tutorial ..

After playing around with the Android SDK , I thought that I should give game development a test drive. After giving Cocos2D a test, I faced the problem of online support, almost all the tutorials I found online were for the iOS version.. so I looked for other Engines made for Android.

Before we start coding, we need to make sure that you have Eclipse and Android SDK installed, if not then use google’s guide for that. You should also give this Hello World example a go to make sure that the SDK installed correctly. You also need need a real Android device, the emulator is far too slow to test on .

Java is essential, if you don’t know Java you may get lost in the middle, also take a look at Android’s Activity life cycle just to have an idea about the order of stuff in there.

If you wanna make sure you are using the latest version of AndEngine, follow this tutorial to build your own jar file AndEngine has moved from Google Code, thus the tutorial linked won’t work anymore you can just download the one I’m using from here, or you can follow my tutorial of getting GLES2.0 but chose master instead [you won’t be using a jar file in that case though].

Let’s get started !

Create a new Android project, I chose Android 1.6 [SDK 4] but this should work on any version.
place the andengine.jar file inside the lib folder (if it doesn’t exist, then create it) and right click on it (from inside eclipse) and select build path -> add to build path.
create a new class, make it extends BaseGameActivity. [Eclipse hint: type BaseGame in the superclass field then ctrl+space for auto complete]

now you should have a class with 4 methods in it
declare those global variables

what we did here is that we prepared the Engine by giving it the proper resolution for the device we are using, the camera represents the the rectangular viewable part of the scene, basically it’s what you see on the screen.

Sprites are 2D images that represents the stuff you see on the screen, they can be characters, bullets, or a background image.
in our game, we’ll need 3 main sprites: Player, target, projectiles(bullets). Aat first we’d need to have images for those, you can use your own images .. or use the ones provided by Ray’s wife Player, Projectile, Target. Go to your assets folder in the project , create a new folder and name it “gfx” and place them inside.

now let’s add the Player’s sprite, we will have it at the left side of the screen, in the middle .. let’s do that !

imagine the BitmapTextureAtlas as a board where you stick pictures on it, we defined it’s resolution to be 512 x 512 pixels and it needs to be a power of 2 (we will need those other areas later).We then set the assets path to be in “gfx/”, you can skip that line but when defining the mPlayerTextureRegion, you’d have to define a full path to the image.

we add more stuff to onLoadScene(), at first we calculate the position of the sprite and create a new player sprite

I kind of copied this method from Dan’s tutorial and modified it a li’l bit, so basically we are determining the minimum and maximum y position for the targets to appear at then use the Random() class to generate a random number so the value of y is still on the screen while the x value places the sprite just before the right side of the screen.

The targets also have a random speed between 2 to 4 seconds to cross the screen, so this won’t be affected by the size of the screen to make the game easier.

MoveXModifier is a modifier that makes the targets move horizontally (across the x-axis). [note: if eclipse complained about deepCopy(), change it to clone() .. deepCopy() was introduced later in AndEngine]

we’ll talk about those linked lists later on.

Now we need to periodically call the addTarget() function, we do this by using this TimeHandler

Test, you’ll have targets coming from the right side of the screen and disappearing in the left side .. our Ninja got company!

Can I kill them now ? (removing sprites)

Not quite yet, we are missing something. The targets move from the right side to the left side, but when they leave the screen [the camera] they stop just outside, they still exist [in the scene] but just outside .. we gotta fix that.

We used an iterator as it seems the safest way to modify a linked list using the remove() method, and if the target left the screen , we simply call removeSprite to delete it. We iterate over targetLL, and then we add everything from the TargetsToBeAdded and clear it, I did this as a workaround cause I was getting ConcurrentModificationException, this way we won’t interrupt the work of spawning targets.

Now let’s register the update handler, append this to the end of onLoadScene()

mMainScene.registerUpdateHandler(detect);

What about now ? (handling touch input)

We first gotta equip our ninja with a weapon, did I hear shurikens ?
add this to our objects

Am kinda too lazy to explain this , so I’ll just “borrow” [read:steal] from Dan’s tutorial

This should look familiar to anyone who didn’t fall asleep in maths class – Pythagoras! Now before we fall asleep with yet more theory, let’s start coding. In the constructor add the following line:

We create the sprite and position it over the ninja. We then work out where the projectile should move to by extending the tap off the screen. This is done by getting the X and Y offset of the tap to the projectile’s starting position. We then get the ratio of Y to X, and simply scale the touch Y coordinate to match the scaled up X coordinate (which is just off the screen).

After working out the destination, we need to work out the duration of the movement – we can’t have projectiles taking different amounts of time just because of the angle they’re shot at. To solve this problem we use Pythagoras to work out the distance the projectile needs to travel, then divide that by the velocity we want. This is because velocity = distance over time, or by re-arranging: time = distance over velocity.

Got it ? :P

Now we’ll need to receive touch events, that will be done by having our main class implement IOnSceneTouchListener
Assuming your activity is called AndEngineSimpleGame, it should be like this

We are only tracking tapping events. Next we put this at the end of onLoadScene()

mMainScene.setOnSceneTouchListener(this);

Run and tap on the screen, our Ninja is a shuriken master !

But .. But .. They are not dying ! (collision detection)

Oh right ! about that we’ll get to that now..
As you should’ve already noticed , we didn’t clean up after the projectiles , they are just leaving the screen and staying there .. we’ll do that with our basic collision detection.

We Loop over all projectiles for every loop over targets, at first we check if the projectile left the screen , if it did then we remove it and continue to the next projectile, if not then we check if they collide or not.

We are assuming here that if a projectile did hit a target, it’d hit one and only one target that’s why we break out of the loop after the collision, we remove the target after the loop.

Using the same technique we used for targets, we avoided the exception [and used more resources]

Give it a test now and let our Ninja enjoy killing those ghosts thingies.

I Have Ears ! (Sound/Music)

Oh, you want some sounds ? ok then .. you shall be given.

We’ll add two sounds, an effect for shooting and a background music, you can use your own audio files or use the ones provided by Ray [and taken from Dan’s site] background music, , pew pew sound effect [note: apparently AndEngine better uses .ogg files, but those wav files worked fine for me].

Place those files in “assets/mfx/” after extracting them , and let’s start editing our code ! [I renamed the “background_music_aac.wav” file to “background_music.wav” do so or make sure you fix that in the code unless you like clicking the famous Force Close button]

If the Menu button is clicked while the engine is running, pause the game [and show that toast] , else resume the game .. give it a try

PWND ! (Win/Fail and Finishing touches)

Game is boring if you can’t win (or lose) , let’s add those aspects to our li’l game, first download those images for Win/Fail that my friend Mazyod created [and place them in “assets/gfx/”] , then declare those

Well .. you broke the barrier of creating games, that’s something [and you have a happy frowning ninja too] , check out the other examples by AndEngine and hit the forums for help.

This was my first tutorial and first blog post too [and was actually my first AndEngine project too XD], I hope you have enjoyed it. If you noticed any mistake or know of a way to do stuff in a better way leave a comment !

When we add the font texture for the score, you forgot to show the mFontTexture creatiobn. I had an error because of that , in the loadRessources() :

add this :

mFontTexture = new Texture(512, 512,
TextureOptions.BILINEAR_PREMULTIPLYALPHA);
( i put the same number of the other but i m not sure!)
if not, there is a bug because of that because mFontTexture doesn’t contain anything :

:) I have an other problem and I don’t know where it comes this time :/
I created the onResume ( onREsumeGame seems to doesn’t exist anymore) and then the onPause and then game crashe directly at the beginning ><
Without onPause it works… I am quite lost here

yeah , because of the structure of the way I handled it .. I kinda had to have two return statements .. feel free to do it in another way
and for the score, you are already doing that inside the method “restart()” ;)

already mentioned that later on in the tutorial “And onKeyDown gets changed a li’l bit again, set the pauseFlag to true after you call pauseGame(), and to false after you unPauseGame() it”
well .. no harm into editing it again

hello I’ve been trying to work off your example here, and have not been able to get the sprite to display at all. scene.attachchild() seems to be giving me the trouble, eclipse says it throws and illegal state exception and Logcat gives me an error claiming “Error while generating scanline”
I would love to get this running, but I’m at a road block if I can’t get sprites onscreen.

Just freakin’ awesome!! Thanks a ton for this! Before this one I was trying to create my own game engine and do all the stuff myself. While that was good for learning, it was taking too much time and I wasn’t able to concentrate on the business part of game development (ahem!). AndEngine is great and greater is this tutorial for starters!

Hi!
Been trying to understand andengine for a couple of days now and your tutorial is the most useful and easiest I have come across.
I just began following it, but found a problem at the very beginning, when it is supposed to show the blue screen, all the emulator outputs is a landscape screen showing “Hello World, GameTestActivity!” (Being GameTestActivity the name of my class). What am I doing wrong?

when you create the class [GameTestActivity] make it extend BaseGameActivity in the create window [or just delete the oncreate() method], your class should not have onCreate() method in it , I’ve updated the post with a screenshot

Extremely beautiful. The code is simple, understandable, and covers a lot of the basics. I cannot thank you enough for your work.

Just one note, the project worked perfectly on the emulator. Later wanted to test it on my galaxy i9000, and the app crashed on the first attempt to launch. Worked perfectly on the following attempts though.

Glad you enjoyed it !
I own the same phone [high 5 ?] and sometimes eclipse doesn’t get updated with all the assets when deploying the app , or it could be a random problem … inform me if it happens again [with the log (stacktrace) from logcat]
and you are welcome :D

even though this is out of the scope of the tutorial [and I gave you a wikipedia page] but here’s a brief
the idea of the linked list is to have a node that points to another node, each node would be a class (or struct) that contains the data and a pointer to the next node i.e.
class node{
string data;
node* next;
}
whenever you need to add a new element, you’d create a new node and make the last node point to this new one , you end up with a list of nodes that are linked to eachothers , and to access a node in the middle you’d have to go from the head and iterate over the pointers till you reach the one you need.
here I used a ready made linkedlist provided by java, you can create your own if you need it
you may need to look up more data structures tutorials to get the hang of it

First thanks for this great and clear tutorial. All is fine untill i got stuck on the part ‘But .. But .. They are not dying ! (collision detection)’. When i update my detect IUpdateHandler to yours i get all sorts of misconstruct errors. Am i doing something wrong or is the code damaged?

urgh , wordpress omitted a small part from code >_<
I changed it back and should be fixed now .. if you have any other issues please post the stack trace you get from logcat [DDMS] (assuming you are not getting compile errors) and your code on http://pastebin.com/ and post the link here
I'll check it for you

I’m pretty sure that I fixed everything :S .. could you give more info about what errors are you getting from this ?
also .. go to the bottom of the tutorial and download the whole project then check if you can figure out what’s the difference .. I can’t exactly pin point what’s wrong in there
if you need help getting the difference , check my previous comment on how to let me know

Thank you for reporting that !
I got no idea what’s happening here .. guess wordpress made some changes or something is getting parsed as HTML tags
tell me if you found any others
and glad you liked it :D

from the Java docs , the descriptor for the iterator remove() method is
“Removes from the underlying collection the last element returned by the iterator (optional operation).”

the removeSprite() method takes 2 arguments , the _target object which is the target we wanna remove, and the iterator.
the iterator goes over the linkedlist objects (it just goes over them , doesn’t copy the contents) so when you remove using the iterator remove() method you are actually also removing from the linked list, and it removes the last object it reached

if you removed directly from the linked list , it’ll throw an exception cause the size of the linked list changed , but if you are using the iterator it’ll be handled properly

[almost] everything in Java is an object, so you may consider the iterator as a pointer going over the linked list

;) Thank you!! my will be uploaded to android in few days using this Engine and will be next big thing i hope!! :D very good tut never got lost :D like in most tut in books or websites :P, thank you!!!!!!!!!!!!!

I am pretty sure I am doing something wrong but I have no idea what. I have gone through the code several times. My problem is in the onLoadResources(). Where you initialize the texture regions.

It appears to draw the images on the screen right then and there. For example, when i play the game, I have the “fail” image, “win image”, “ninjas”, “shuriken”, “enemies” and every single image i initialize already drawn.

My fix for it was to change the coordinates when I initalize them too off the screen. i used “mCamera.getWidth()” for the x value instead of the one you used and i changed up the Y value too. So now my game works like yours but I would still like to know the cause of the problem.

Hi ! i am new in AndEngine… and your tutorial helped me a lot! However after i did everything you did and its done good, now i am messing with how to do the image background (another image that i add)
I know i need to do sprite first off all, but when i add the sprite to between mMainScene = new Scene(); and return mMainScene; he just give me ann error (Force close) but for example if i add the sprite to mPauseScene or mResultScene its show up without problem, cant understand… :(
So waiting for answer, thank you soo much :)

I’m not exactly sure how you are putting the background image , but if you are adding it as a big sprite then you can’t add it inside onLoadScene cause you are adding the image to the scene when the scene is not ready
if you wanna add it as a normal sprite then attach it inside onLoadResources().
if it’s still not fixed I’d appreciate if you paste your code on http://pastebin.com/ and gave me the link
also if you checked the DMMS/Logcat , it should give you a stack trace of the error and why it happened [the exception name] provide that too as just saying “ForceClose” is not helpful
you might wanna continue with the tutorials series too, it includes some neat background and animations later on :P

Tnx for answer! Well from now i have the source code that you give with the tutorial (I wrote everything step by step and everything was good but after some mess with the code he gave me alot of errors so i downloaded the source code )
and of course i add it in onLoadResources(). to…
Can you tell me how can i add big sprite (Or is it the same as normal Sprite function ?) again thank you !

adding a big sprite is the same, just make sure you understand how BitmapTextureAtlas works and that you have enough space to add that
and again, if you continued with the tutorials series [there are 2 more tutorials that continue on this one, the next one got a link in the last section of this one] you would see how to add a big sprite

Nice tutorial. Just looking for some help with an issue I’m having with installing the extensions for the game engine. There are no errors in the code for the game engine itself, but as far as the extensions are concerned, they’re registering a ton of source code errors. Any idea on how to fix this? Thanks in advance.

are you talking about extensions like multiTouch and box2d ?
in tutorial V2.0 I show you how to install multiTouch extension [more or less :P] but it appeared that the multitouch source code actually includes the andEngine source code too so you’d have to get rid of that .. at least that was how the case was with me

if you are talkin about something else, then would you give me more info about what are you talkin about ?

Hello Jimmar,
How are you? The tutorial is awesome and helped very much.
i want to take ur opinion about something, Is it better to make one IUpdateHandler to detect all events or to make 2 or more handlers (one for sprites, one for bullets,,..etc)?

glad you liked the tutorial
I’m not quite sure , but I think that it’d be better to have one update handler [main game loop] unless it doesn’t work well [if it lags or some actions needs priority] then use multiple

Hello Jimmar,
Thanks for your reply,
Please i need your help with something strange. i need the .jar extension files of multiTouch and other extensions but i failed to get them. i tried to clone the extensions from google.code but i failed :(
if u have them or know how to get them, please tell me.

Hello Jimmar,
i have put a pause in my game as u teaches us in ur tutorial, but i have a problem. i put sprites in the pause scene and touch listener on them, (ex: restart images when the player pause the game i put a sprite with restart image) but it doesn’t respond!!!
i have enabled the touch in the scene :
pauseScene.setTouchAreaBindingEnabled(true);
and register to the sprite :
pauseScene.registerTouchArea(go_btn);
the image of restart appeared but no touch. Could u tell me why this issue? i guess it is because the mEngine.stop() ?
waiting for ur reply

Very good tutorial and helped my understand the basic concepts of the andengine examples and how to build the basic game, I actually was able to add some personal touch such as sound upon hitting the target ad sound when loosing / wining the game. This was very helpful indeed.

I have answered this in a previous comment .. but oh well
you can put a sprite with the same size as the screen on the back ..
you can also continue with the tutorials to see how to make a moving background

I can’t figure out what’s wrong with those info only , could you at least tell me what kind of errors are you getting ?
keep in mind that this is done on AndEngine GLES1.0 not GLES2.0 , if you are using GLES2.0 this won’t work without modifications
try using the jar file that I provided and see if that solves the problems

I did use your jar file in /lib, i’m not that good at coding but when i follow every tutorial i do as people write it and still get all these errors on every line? Maybe i have installed eclipse and so on wrong, if i write some lines of codes that is being used here. It will give X dots everywhere and tell me to maybe create a class or they have another quick fix for it. Every god damn line, if you know anything about it i would be very greatful! Thanks.

Try cleaning the project [project -> clean]
also , are you sure you installed andEngine properly ? have you managed to run your code till the blue screen ? [if this didn’t work then you might not have added the jar file to your build path, go to it in eclipse and right click on it -> build path -> add to build path]
and before that , did you run an android hello world program to make sure that the android sdk is installed properly ? [you may wanna follow an android beginner tutorial first to make sure it’s working]
and don’t copy and paste code , write it on your own :D

Very good tutorial for a beginner and thank you for making it it!
I’m trying to make the part with the blue screen to test if the engine works but some code lines have errors (the x dot). I added those two permisons to the manifest and installed andEngine.jar ( right click on it -> build path -> add to build path ). Also I made a few Hello World android apps in eclipse and it worked so I don’t have a problem with eclipse. If you know what is wrong is please tell me!

great tutorial as i read it and basing from all the comments! but the thing, i haven’t tried it yet since i am really newbie in using andengine. Just need a little help Jimmar, can you help me how to install andengine /GLES1.0? i already have my androidSDK and eclpise up and running. also done with hello world tutorial, and it works just fine. your reply would be much appreciated! thank you again and God bless!

you can use the tutorial I linked to that installs GLES2.0, just chose “master” instead of GLES2.0
or you could just use the andengine.jar file that I provided in this tutorial
you could also skip this whole tutorial and jump to my jimvaders tutorial on AndEngine GLES2

Hi JiMMaR,
First, sorry for my poor English =S
Second, thks for this incredible tutorial!!! =D
And to finish… I try the game in the Eclipses Android Emulator (android 2.2 version) and it runs right but when i try it in a real mobile phone (with android 2.3) it crashes when i try to execute.
Thks for all and continue with this tutorials, they are rly ussefull!!!!

Those Info are not enough , you need to check what the catLog says regarding the crash [the cause of the crash]
if you couldn’t figure it out , use http://pastebin.com/ to paste the output and put the link here

I was excited to find this great site. I need to to thank you for your time for this fantastic read!! I definitely really liked every bit of it and i also have you book-marked to look at new information on your blog.

err .. This tutorial was meant to be followed , and not imported as a whole
also , this is for GLES1.0 , you should go to the other tutorial called jimvaders for GLES2.0 tutorial
I don’t really know exactly what’s wrong with your project

I was asking my self how to implement different levels. I was thinking to use the CameraScene object and do something similar as you do to pause the game. Do you think this is the right way? Do you know any tutorial for creating different levels in the game?

I have 3 solutions that are coming to my mind
1- have each level implemented as a different scene, you get to have full control over what happens in each level [add a camerascene for a loading page to appear at the end of each level and a similar one to be attached at the start of the level to mimic a transition]
2- if your levels only have different enemies , just change the enemy layer, attach different enemies to a new enemy layer and replace the one you already have with the new one [easiest solution :P]
3- if the game grows big , it’d be easier for the long run to be able to design your levels by reading from external xml/txt file where you design the levels there

I can’t seem to recycle anything? Bullet, and targets both aren’t being recycled. I’ve added the Iupdatehandler, registered it on createscene, and targets are being added, and so are bullets.
Is this because I’m not using GLES 1.0? I’m using 2.0, and I know you made a new tutorial, but I just find this a little better. Can someone help me out? I’ve created 3 projects files already in case if I had made any mistake, but nothing seems to be working. It still shows in Logcat that target, and bullets are not being recycled.

okay.. weird enough, I just booted eclipse today, and everyone is working fine. sometimes.. i just feel like setting eclipse on fire. :> Thank you so much for the tutorial! :] We all really appreciate the time and effort you put into them. keep it up, mate.

hi, jimmar
sorry in advance if my english bad .. :)
I tried to make a RPG game in android and using a background image. I build it in android version 2.3.1 (gingerbread) but still error projectku … is there a tutorial for the game with a background image?? thanks for the advice ..

if you continue with this series of tutorials, you should see how to create a moving background image in the 3rd tutorial [in Simple Android Game Tutorial V2.0]
but if you want a static image , just put a sprite that covers the whole thing
don’t use the background functions, a simple sprite would do fine

Thank you, I have just been searching for info about this subject for a long time and yours is the greatest I’ve found out so far. However, what about the bottom line? Are you positive concerning the supply? dkeebfbdeefk