Skip to content

Getting Started: Working with Images

Next, let’s take a look at working with images.  AndEngine has a few tools that are important for loading images into memory, setting them up for use, and making sure they work well and efficiently.

Why it can’t be simple

When I got started with game programming, I tried to just give each sprite an image whenever it spawned.  I didn’t want to have to deal with texture regions, so I simply ignored them.  However, when it actually game time to run my game- it ran like garbage.  Everything worked much more slowly than it should have, because not only did I not tell the game not store the pictures in memory- I also had them just a few pixels too big for Android to work with.  I didn’t put the effort in to understand how to work with image, and my performance suffered as a result.  Hopefully, we can avoid letting that happen to you!

What are Textures?

In modern game environments, the system’s memory allocates in size to the power of 2.  What this means for you as the programmer is that it is best to make your pictures as close to the power of 2 as is possible.  Therefore, your image can be 2×2 sprites, 4×4, 8×8, 16×16, 32×32, 64×64, 128×128, 256×256, 512×512, 1024×1024, ect.  Also, the dimensions don’t have to be the same- you can have an image that is 512×256, 4×1024 (though I’m not sure why you would want that one)- without wasting memory.

So, what if it doesn’t end up a power of two?  The system allocates that memory as empty memory, and it is wasted.  This is one of the reasons why my game took up so much memory- because my 260×260 images were taking up almost twice the amount of space that they actually occupied in memory!

This is where Textures and TextureRegions come in.  AndEngine allows you to dynamically fill in those blank spaces with different images in order to make a single Texture Atlas- one image, with each region defined as a different section of that image.  By using a TextureRegion, you can save memory in your app, while keeping the image defined in memory- thus resulting in an image that stays in memory and can be used for dozens of sprites with very little slowdown at all!

So- what are the pieces of code necessary to put all this together?


The BitmapTextureAtlas is the picture that is loaded into the memory.  It will be your final product- and as such, it needs to be defined first.  First, it’s a good idea to define it in the base of the class with the other fields and constants, like so:

	private BitmapTextureAtlas mBitmapTextureAtlas;

Next, we begin to work with it in the onLoadResources() section of the code like this:

	this.myBitmapTextureAtlas = new BitmapTextureAtlas(512, 1024, TextureOptions.BILINEAR_PREMULTIPLYALPHA);

When the BitmapTextureAtlas is defined, it includes three variables.  The first two are the height and width of the texture atlas.  In this example, it is given a height of 1024 and a width of 512.  The third is a quality of how the picture will be rendered.  For most uses, TextureOptions.BILINEAR_PREMULTIPLYALPHA will do just fine here.

There is one last thing I would like to mention in this section: how to set the base path.  It’s a good idea to place your image in a separate path to keep your project organized, and that includes putting all your images in a separate folder.  It can simplify your code and make any future changes easier if you set the base path of your texture region factory (where your images are stored) like this:


There you have it!  This is how you create your Bitmap Texture Atlas.  Next, we need to load it with images!


To place an image onto your atlas, you need to create a TextureRegion.  Just like TextureAtlases, TextureRegions should be defined in the base of the class as they will be used in multiple parts of the app, like so:

	private TextureRegion myTextureRegion;
	private TextureRegion myBackgroundTextureRegion;

Then, they should be defined in the onLoadResources() section of the app- like so:

	this.myTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.myBitmapTextureAtlas, this, "myImage.png", 0, 0); 
	this.myBackgroundTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.myBitmapTextureAtlas, this, "myBackgroundImage.png", 0, 185);

Okay- what’s going on here?  What we’re doing is telling the BitmapTextureAtlasTextureRegionFactory (the device built into AndEngine that puts the textures together) to add an image to the texture region.  To do so, it takes a number of inputs:

(1) the Texture Region you want it to be a part of

(2) the base context (this usually works fine here)

(3) the texture to be loaded into the atlas

(4) the X offset of the image on the region

(5) The Y offset of the image on the region

Most of these are self-explanatory, but let’s take a quick look at #4 and #5- they’re used to let the image factory know where in the texture region to place the particular image.  If you leave this at 0, the second image will overwrite the first one!  If you run into a situation in which an image is partially obscured by another image when loaded, the offset is almost definitely the problem- just make sure to allocate things so that they don’t run into each other!

Loading into the engine

There is one last step before the setup is complete- we need to load the bitmap texture atlas into the engine.  To do this,

	this.myEngine.getTextureManager().loadTextures(this.myBitmapTextureAtlas, this.myBackgroundTextureAtlas);

This code loads the texture atlas into the engine (with an extra atlas, myBackgroundTextureAtlas, stuck in there to show you how to add multiple texture atlases at once).

Which Image Files to Use

So, what do we put into our Texture Regions?  It may be tempting to use the smallest format available- such as a compressed jpg, or a gif- but it’s not always the best idea.  My suggestion- in most cases, use Png.  Png files have a number of benefits to them- they are lossless, which means you’re going to be getting the image at full quality, and they have transparency, meaning if you have any places where the user should be able to see through the sprite, they will be able to do so.  (These make Png such a popular choice that some even say it stands for Please not Gif!)

For working with your images, the best picture editing program is Photoshop, but if you’re an amateur developer, you’re probably not ready to shell out the hundreds of dollars required to purchase a professional copy.  If you are looking for a good free picture editing program, the two main alternatives are and Gimp.  There is also a handy free flash-based picture editor that works quite well called pixlr– though you should be aware that though it has great capabilities, you have to intentionally save it with layers, or they will be lost when closed.

Hopefully these tools will have your pictures up and running smoothly- you’ll need it for our next guide, Getting Started: Backgrounds!


Getting Started: Sound and Audio

Let’s face it: sound is a big deal in games.  If you’ve ever played any video games, you know what I mean; some games are made by their music and sound effects; others are broken by them.  Now, you may want to think twice before making audio essential for your game- in the smartphone environment, many users will be muting their music.  Nevertheless, it is a big deal that can really make (or break) a great game.  So, the question is- how do you include music and sound effects in your games?

Enabling Music and Sound

Okay, so the first thing you need to do is tell the engine that it needs to look for sound.  In your onLoadEngine() code, include the bolded section of the following code:

return new Engine(new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), camera).setNeedsSound(true));
return new Engine(new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), camera).setNeedsMusic(true));

And that’s all there is to enabling music.  With this, you’re ready to import your music and let it play!

Importing Music and Sound

The next thing to do for working with Music and Sound is to import it into the onLoadResources() section.  If you are looking to use a sound, try this code:


try {
	this.mySound = SoundFactory.createSoundFromAsset(this.mEngine.getSoundManager(), this, "mySoundFile.ogg");
} catch (final IOException e) {

For music, use this code:

try {
	this.myMusic = MusicFactory.createMusicFromAsset(this.mEngine.getMusicManager(), this, "myMusic.ogg");
} catch (final IOException e) {

In these examples, we have the audio placed in the folder mfx/ in order to make sure the project is organized- the first line of both examples is telling AndEngine to look in that directory.  Next, we have the code try… catch- this is an essential part of code (required by AndEngine) that makes sure the audio is there- but doesn’t cause your app to fall apart if it’s not.

Next, within the try, you define a variable- in this instance, Sound mySound and Music myMusic.  When given the music manager, context, and sound/music file, it puts it into a format that AndEngine can work with.  You’ll see one last difference between the music and sound file- that the music is given the command setLooping(true).  This is the first glimpse of one of the benefits AndEngine brings in its ability to deal with music and sound.

NOTE: there are a number of things that can cause music or sound not to play in a game.  One is a lack of resources: if the Android runs out of resources, it will often take sound out- because of this, it is important to make sure you use a bitrate that will keep your sound file from being to large.  The free program Audacity is a good resource for editing the fiiles down with the maximum retention of quality.  However, the more common reason (in my experience) for files not to play is that they are given the play command before the song is loaded.  Therefore it is important to place your music in onLoadResources, and the command to play it in onLoadComplete or later so that the user isn’t greeted with silence.

Playing Music and Sound

Once you load the music and sound, playing them is simple!  For the sound, play it like this:;

However, there is much more that can be done than just playing!  Here are a few of the most useful commands:

myMusic.pause();  myMusic.resume();  myMusic.stop();

These ones are pretty straight-forward- they pause, resume, or stop the music from playing.


If the song our sound file is playing, it returns true; if not, false.  It can be useful with sound effects- if it’s playing, stop it before playing again, so that you don’t end up playing too many sound effects at once and crashing your app.

myMusic.seekTo(int millisecond);

This code jumps the sound file to the millisecond defined by the int.

myMusic.setVolume(int volume) or (int leftVolume,int rightVolume);

If given one variable between 0 and 1 (in percent), this code sets the volume of the music to that number.  If given two variables, it sets the left volume and right volume separately.

myMusic.wait(long millisecond);

This code pauses the audio, then waits for the specified number of milliseconds before resuming it.


This code sets a listener that runs a section of code when the music has finished playing.

Legal Issues Concerning Music

Fantastic!  you may be thinking to yourself.  I’m going to go use one of my favorite game soundtracks for my game, such as the theme from Sonic the Hedgehog or Katamari Damacy.  I have bad news for you: if you do that, you’re most likely on your way to a lawsuit.  One of the biggest issues for Android and iPhone games is avoiding breaking legal copyright.  In the future, I’m hoping to write an entire post on the issue; in the meantime, I need to warn you- do not use anything copyrighted.  Best-case scenario, your game gets pulled from the market.

Check the license of every song you use.  Make sure you know whether or not they are available for use.  And if you’re not sure, it’s probably best to find something else- some other music that isn’t copyrighted.  For some samples of free music, check out AndEngine user Whalabi’s guide here.

Getting Started: Working with Motion

Okay, so now that we’ve taken a look at the first kind of input, touch, let’s look at the other: Acceleration!  Every Android machine includes an accelerometer that can measure movement of the device in 3 directions- assuming you are facing the device, the X axis tracks movement tilting to the left and right, the Y axis tracks movement tilting up and down, and the Z axis registers movement forwards and backwards.

  (Image from Google)

What this means for you as a developer is that, given the right code, you can detect any movement in any direction on the device.  So the next question is: how?

Including Accelerometer Input

Using the accelerometer is quite simple.  First things first: your app needs to include accelerometer input.  To make this happen, start by implementing it in your class definition like this:

public class myClass extends BaseGameExample implements IAccelerometerListener {

This bolded section tells your game that you will be using the accelerometer, so it should include the code that makes it listen for that input.

Enabling and Disabling the Accelerometer

There’s another thing concerning the Accelerometer that you need to know about: enabling and disabling it.  At some point (likely in the onLoadResources section of your code), you’ll need to enable the accelerometer in code.


If for some reason, you want to stop or start using the accelerometer temporarily, you can use the code:


Now, the next question is: how do we use it?

Reading Accelerometer Input

Once your activity is setup to implement IAccelerometerListener, include code like this in the base of your class:

	public void onAccelerometerChanged(final AccelerometerData myAccelerometerData) {
		mySprite.setPosition(mySprite.getX() + myAccelerometerData.getX(), mySprite.getY() + myAccelerometerData.getY());
		if (myAccelerometerData.getZ() >= 0) { mySprite.setVisible(true);}
		else {mySprite.setVisible(false);}
And that's really all there is to it.  In this example, whenever the user moves the device, this code is called.  It moves mySprite along with the orientation of the device (on the X-Y axis, at least), simple as that.  It then sets the device to visible if the device is moved forwards, and invisible if moved backwards.  One thing users often do with this is to use the device to set the gravity relative to the accelerometer- for more information on how to do this, take a look at AndEngineGuides, or stay tuned- getting started with Physics is coming soon!  
With this, you have the tools needed for multiple activities- movement based on device orientation (such as in  doodle drop or a ball labrynth) or action when the device is shaken (such as rolling a die).

And with that, you should have the tools necessary to begin experimenting with the accelerometer!  Up next: Getting Started: Sound and Music

Getting Started: Touch Events

Okay, so you have the framework of your game built, and you have your sprites floating around, let’s make them do things!  With most Android phones, there are two major ways of performing input: touch and accelerometer.  These are the two input methods that are most common for AndEngine games, and both can be very beneficial to a great game!  In this guide, we’re going to be taking a look at how to deal with touch events.

Scene Touch Events

Let’s start with scene touch events.  Fortunately, AndEngine has some quite useful tools that help us handle our touch events, so most of your work is done for you.  In my experience, there are really two main ways of dealing with touch: working with touch on the entire scene and working with touch on a single object.  An example of code that you would want to work with the entire scene would be my game, Rhythm Battle- the ship moves to wherever you touch on the screen.  An example of when you would prefer touch with a single object would be the game Math Monkey, where the user taps moving objects in a specific order to win.  Let’s begin with some sample code for working with touch on a scene- this code would be placed in the base of a class.

    public boolean onTouchEvent(MotionEvent event) {
        int myEventAction = event.getAction(); 

        float X = event.getX();
	float Y = event.getY();

        switch (myEventAction) {
           case MotionEvent.ACTION_DOWN:
           case MotionEvent.ACTION_MOVE: {
            	mySprite.setPosition(X, Y);
           case MotionEvent.ACTION_UP:
        return true;

Here is what is happening in this code: onTouchEvent(MotionEvent event) is called when the user touches the screen.  The location of the user’s touch is given the name MotionEvent event (though, of course, you could name it whatever you wanted).

Now, the first thing we want to do is figure out what has been done by the user- a touch, a movement, or lifting a finger.  We do this with the command event.getAction(), which returns an event (in this case, myEventAction).  In this example, I’m using a switch to determine exactly what kind of action was.  There are a number of different touch event actions, but I’ve found the three most useful ones to be:

MotionEvent.ACTION_DOWN-  this code runs when the user first touches their finger down on the screen.

MotionEvent.ACTION_MOVE- this code will run whenever the finger is moved along the screen- such as to drag a character or item from one place to the other.

MotionEvent.ACTION_UP- you guessed it- this code runs when the user lifts their finger from the screen.

It is worth noting that in most cases, it is seen as a best practice to have buttons activate on the ACTION_UP command, rather than the ACTION_DOWN.

Another thing you’ll often need to know in game programming is exactly where the user touched the screen.  If, for example, you have a character that jumps to wherever the user touched the screen, the way you would determine where the touch was located is through the event.getX() and event.getY() commands.  These return an X or Y coordinate as an int.  (NOTE: sometimes the location on the screen doesn’t exactly correspond to the touch event due to the way AndEngine resizes the scene to fit the size of the phone- usually some basic addition or multiplication will place your sprite in the proper location)   You can then do whatever you would like with these coordinates- such as in this example, where we proceed to set the x,y position of sprite to that of the touch event. A final note- You may notice at the end that we return true; this tells the Android that the touch command has been processed.  Therefore, if this code runs, returning true, the Android will not look for any other code that the touch action may run (for example, if there is something underneath the scene).   This can be useful if you have stacked items but only want the touch action to effect the item on top of the stack, or if you want the background to react to a touch but not interfere with the game.

Item Touch Events

The other type of touch event is a TouchListener set on an individual item- such as a sprite.  When you declare the sprite (usually in onLoadScene), do so like this:

		final AnimatedSprite mySprite = new AnimatedSprite(100, 220, this.mySpriteTextureRegion) {
			public boolean onAreaTouched(final TouchEvent pSceneTouchEvent, final float pTouchAreaLocalX, final float pTouchAreaLocalY) {
				this.setPosition(pSceneTouchEvent.getX() - this.getWidth() / 2, pSceneTouchEvent.getY() - this.getHeight() / 2);
		                int eventaction = event.getAction(); 

		                float X = event.getX();
		                float Y = event.getY();

		                switch (eventaction) {
		                   case TouchEvent.ACTION_DOWN:
		                   case TouchEvent.ACTION_MOVE: {
		            	        this.setPosition(X, Y);
		                   case TouchEvent.ACTION_UP:
				return true;

And there is one more extremely important part:  Near the end of your OnLoadScene, there are two lines of code that are necessary in order to register with the scene that touches will be recieved: scene.registerTouchArea, and scene.setTouchAreaBindingEnabled.  Here’s what it should look like in your code:

I made up a second sprite (mySecondSprite- original, I know) in order to show you that though each sprite needs to registerTouchArea, setTouchAreaBindingEnabled only needs to be set to true once. 

These two lines of code are simple:

The first, registerTouchArea, tells the scene that this sprite needs to accept touch input.

The second, setTouchAreaBindingEnabled(true), tells the scene that when the user touches an object, that should be the object that the touch deals with-  even if the user drags their finger away.  For example, if you had a sprite that moved when dragged (as is the case in the above example), but you moved it under another sprite, if setTouchAreaBindingEnabled was set to false, the touch would shift to the other sprite instead.  With it set to true, the first sprite would remain touched.  While a few apps may want to have this set to false- such as an AndEngine piano- most will likely need it to be set as true.   

As you can see, beyond a few simple differences, the way a Sprite Touch Event works is a lot like the way a Scene Touch Event works.  Even the way the TouchEvent is handled is the same; the only difference is that a sprite touch event is defined when the sprite is created, and its touch area needs to be registered.  

Order of Call

So, you may be wondering- what happens if two items with touch enabled are touched at the same time?  The answer is simple: it depends on which is registered as a touch area first.  If, for example, you register a picture of a banana first and helicopter second, and then you throw the banana at the helicopter, the banana would register the touch first.  If the banana returned true, the touch event would then end.  If the banana returned false, however, the helicopter would then receive the touch.  If both returned false, then the scene would receive the touch event- in my experience, it always goes last.  However, if either the banana or the helicopter returned true, the scene would not receive the event.

Touch events are an important part of most games- with a mastery of this skill, you have another tool under your belt for making a great AndEngine game!

Up next: Getting Started: Accelerometer Events

Getting Started: working with Sprites

So, you have AndEngine set up, and you have your project put together- so the next question is- how do you put things onto the project?  Well, the most common object to be placed in a game world is a Sprite.  A Sprite is, simply put, any pre-rendered two-dimensional object that you place on the screen.  They work something like pictures, with one major difference: sprites can interact with everything.

Types of Sprites

To begin, let’s look at the different kinds of sprites.  In AndEngine, there are 3 major kinds-

(1) A Sprite.  This is the most basic kind of sprite.  It mostly just sits there.  Unless its picture is manually changed, it stays the same.  Thanks to AndEngine, it can do anything a normal sprite can do, but it doesn’t have any of the special qualities the other sprites have.

Sprites are usually defined in onLoadScene like this:

	Sprite mySprite = new Sprite(startingX, startingY, this.myTextureRegion);

This example will create a sprite named mySprite whose top-right corner is located at (startingX, startingY)- both of which need to be defined as integers.  The image presented on mySprite will be myTextureRegion.  For more on Texture Regions, check the Texture Region Guide.

(2) The second kind of sprite is a TiledSprite.  A tiled sprite is somewhere halfway in between a regular sprite an an animated sprite- it doesn’t animate at a regular rate, but it takes a tiled texture region, and with a command (found below) can switch between its different tiles.  TiledSprites are defined in onLoadScene like this:

	TiledSprite myTiledSprite = new TiledSprite(startingX, startingY, this.myTiledTextureRegion);

For the most part, you can see that it looks- and works- just like an ordinary sprite, with the only difference being that it uses a TiledTextureRegion instead of a normal texture region- at first, it will only use the first tile, but when given the commands found below, it will change what it looks like.

(3) The third kind of sprite is the AnimatedSprite.  If you’re making a game, you’ll probably be using at least one AnimatedSprite- it takes in a series of images and plays them at whatever speed you specify, one after another, often looping (though they can be set not to.)

Animated sprites are defined in onLoadScenes like this:

AnimatedSprite myAnimatedSprite = new AnimatedSprite(startingX, startingY, this.myTiledTextureRegion);

So, this still looks pretty much the same- startingX, startingY, and myTiledTextureRegion.  However, this time, instead of being shown as a series of tiles, it is shown as an animation (based on the animation speed you set it to after it’s initialized)- check the code below to see how this works.

Basic Sprite Commands

Now that we know the differences, you may be wondering- what is a sprite?  Honestly, a sprite is little more than a rectangle which has its face set to a particular image and is given a few particular actions useful in games.  As a matter of fact, the base sprite class extends BaseRectangle, so any commands that will work on Google’s BaseRectangle will also work on a sprite.  A sprite differs from BaseRectangle, however, when it comes to movement, size, and interaction- and that’s where some of AndEngine’s special features shine.  Here are a few special commands that work with sprites:

scene.attachChild(mySprite); alternatively, sprite.addToScene(scene);

This line would attach the child to the scene, officially making it a part of your app!  This should also be done in onLoadScene.

mySprite.getX, mySprite.getY, mySprite.setPosition(x,y);

These are commands that will give or set the current coordinates of the sprite.  Therefore, if you wanted to move something left, you could get its x position, subtract a number, and then set that position back with the command sprite.setPosition(sprite.getX-10, sprite.getY).


Makes the sprite larger or smaller, based on a power of X (for example, setScale(2) would make it twice as big, while setScale(0.5f) would make it half as big.


Rotates the sprite by x degrees.  For example, setRotation(90) would turn it sideways, while setRotation(360) would have no effect, as it would take it full circle.  


This command can prove valuable when you want to remove a sprite, but leave it in memory.  An example of how this is useful is this: say you have a game where you fire bullets.  Every time a bullet leaves the screen, you need to remove it, but within seconds, you’ll be creating another.  Rather than taking the extra processing power to remove the enemy and make a new one, it is better practice to remove the bullet, then reuse it next time you need a bullet.


This is a command given for a tiled sprite which changes its image to the next tile.


This is a command given for a tiled sprite which changes its image to a specific tile.



This command will remove your sprite from the scene properly.  Sometimes, you may want to just use mySprite.setVisibile(false); Using this command will help reduce memory leaks (which are a big problem, and can even break your game if they have multiple levels back to back).

myAnimatedSprite.animate(x, int loopingCount);

This is a command given for animated sprite which starts it animating with the frame length X (in milliseconds).  If a second variable is given (as an int or boolean), it will repeat that many times.


This is a command given for animated sprite which stops its animation at the frame x.  If x is left blank, it stops it at the current frame.

This is a command given for animated sprite which starts it animating with the frame length X (in milliseconds).

There are hundreds of commands that can be used with sprites- these are simply some of the most common ones to get you started.  As you can see, AndEngine’s sprite class is a powerful tool that is essential for any game.  If you’re interested in using physics or creating an array of sprites (such as multiple enemies or targets), check the AndEngineExamples, use Google to find a guide, or check back here in a few weeks- both of these are planned topics.  If you have any other questions, feel free to comment, e-mail, or head over to the forums- the community will help you with anything you need!  Up next: Getting Started: Input: Touch Events and Motion Events.

Getting Started: The Work Order of AndEngine

Elements of BaseGameActivity

Before getting started with your AndEngine project, let’s take a look at the flow of BaseGameActivity.  It’s very likely that at least a large portion of your app will extend BaseGameActivity, so it’s important to understand how the pieces of it fit together.

Each BaseGameActivity must contain 4 major elements: onLoadComplete, onLoadEngine, onLoadResources, and onLoadScene.  We’ll look at these in the order of which they are called, and then we’ll look at a few additional elements that may be useful.


First, OnLoadEngine is called.  This command is where you define your engine.  Usually, it will look something like this:

	public Engine onLoadEngine() {

		//sets up the engine = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT);
		final EngineOptions engineOptions = new EngineOptions(true,
				ScreenOrientation.PORTRAIT, new RatioResolutionPolicy(


		return new Engine(engineOptions);


This example sets up an engine with a Camera (utilizing 2 values that must be defined in the file) and some options (which are, in this instance, whether or not the game is fullscreen, the screen’s orientation, the resolution, and the camera used by the scene).  Before I return the engine, I make sure the game knows that it will be using both sound effects and music.  What this code does is essentially create a blank canvas on which the rest of the game’s code is written.


Next, OnLoadResources is called.  In this section, you pre-load all the resources your game will be using regularly.  This can be beneficial because, as you know, games often reuse sprites and textures.  For example, if you have a character that shoots a laser at a rate of 2 times per second, it would be far more inefficient to create each laser as it is made.  In addition, if you were to load all your resources into memory after the game had begun, you would experience major slowdown whenever a new resource is loaded- and that’s bad.  In some instances, it could even cause instability, or cause things to function incorrectly- my game requires multiple music files to be playing at the same time, and even a tenth of a second of desynchronization would sound terrible.  Therefore, it’s just a good idea to get that out of the way here- load as many resources as you foresee using.  Here’s a sample:


	public void onLoadResources() {

	LaserFrequency = 4;
	CurrentScore = 0;
	HitPoints = 10;

	this.mBuildableTexture = new BuildableTexture(512, 512, TextureOptions.DEFAULT);
	mLaserTextureRegion = TextureRegionFactory.createFromAsset(this.mBuildableTexture, this, "laser.png");
	GameActivity.mShipTextureRegion = TextureRegionFactory.createTiledFromAsset(this.mBuildableTexture, this, "maincharacter.png", 4, 1);
	GameActivity.mEnemyTextureRegion = TextureRegionFactory.createTiledFromAsset(this.mBuildableTexture, this, "enemy.png", 4, 1);

	font_texture = new Texture(256, 256, TextureOptions.BILINEAR);
	font = FontFactory.createFromAsset(font_texture, this,"pf_tempesta_five.ttf", 60, true, Color.BLACK);

	this.mEngine.getTextureManager().loadTextures(mBuildableTexture, font_texture, font_texture);

	GameActivity.explosionSound = SoundFactory.createSoundFromAsset(this.mEngine.getSoundManager(),this, "explosion.ogg");
	GameActivity.gameOverSound = SoundFactory.createSoundFromAsset(this.mEngine.getSoundManager(), this, "gameover.ogg");

Okay, so in this example, I’m doing 4 things.

(1)- I’m setting up a few variables.  It’s always a good idea to set all your variables in the onLoadResources section, so that you don’t end up with any leftover values causing you trouble.  For example, on my first game, I forgot to set the score variable to 0 in onLoadResources, and so every new game, the score was just added to the previous one.  Resetting it in onLoadResources fixed it immediately!

(2)- I load a few textures.  I load a character texture, an enemy texture, and a bullet texture here.  You may notice the character looks different than the bullet- that’s because the character is animated.  We’ll discuss this further later.

(3)- I load a font for use in in-game text, such as score displays or progress updates.  Chances are, you won’t want to use the built-in fonts for everything.  Fortunately, AndEngine has a great font manager- more on that to come.

(4)- lastly, I load a few sound files.

If any of this doesn’t make sense to you, don’t worry- we’ll be getting there soon.  In the meantime, just understand that this is the place where you load all the resources that you will put into your app.


Third, OnLoadScene is called.  This is where all your behavior is defined.

	public Scene onLoadScene() {
		this.mEngine.registerUpdateHandler(new FPSLogger());
		level.getScene().registerUpdateHandler(new TimerHandler(((20-CurrentLevel)/5), new ITimerCallback() {
			public void onTimePassed(TimerHandler pTimerHandler) {

		level.getScene().registerUpdateHandler(new IUpdateHandler() {
			public void onUpdate(float pSecondsElapsed) {
		//fires the laser and spawns some of the enemies based on upgrades
		return level.getScene();

So, in this example, we started by setting up the FPS logger, then added the background, a health bar, two update handlers (one to make enemies attack at a regular interval, and one to check for collisions every frame), and a ship to the scene.  This should help you understand a bit of what goes in OnLoadScene- the items loaded in OnLoadResources are placed and prepared for action!


Finally, OnLoadComplete is called.  This where, once everything is loaded, you define all the movement and actions that make the game do what it should do.  For example, here is where you would put, or start any animations you want to begin when your game starts.

Hopefully, this will give you a good idea of how an AndEngine app flows!  Next time, we’ll be taking a look at different kinds of sprites, and which ones you want to use!

Getting Started: Installing AndEngine

Note: these instructions are for the GLES1.0 version of AndEngine.  It provides greater compatibility and speed in most instances, though is no longer updated.  If you are interested in learning more about GLES2.0, check out

The first place to begin with AndEngine is: getting everything running!

Before taking these steps, make sure you have Eclipse running the latest version of the Android SDK.  If you’re new to Android and want a simple guide to get started, check Google’s documentation.  (If you still have any questions, feel free to email me or ask in the comments.)

Okay, so once you have Eclipse running with the Android SDK, the next step is to download the AndEngine source.  There are two ways to do this:

(1) To download the source as a JAR file here.

NOTE- This version of the JAR file is not the latest- it is not updated often.  If you want the latest version of AndEngine, check out option (2)…

In order to include the AndEngine code in a project, go to the project’s properties (right-click the project in the Package Explorer) and go to the Java Build Path tab.  From there, click “Add External JARs…” and select the JAR file you downloaded.  From there, you can import any android code.  This method is substantially simpler, with one simple downside: you can’t actually view or edit the code.  To do that,  you must…

(2) download the source as a part of an Android project here.

Before we get started: In order to download the set, you’ll need to install the Mercurial plugin.  Direct the Eclipse Update Manager to:

and install Mercurial Eclipse (the installation should be similar to installing the Android SDK).  It warned me that I was using unsigned code: I haven’t had any trouble with it, and it’s a trusted app among developers, so if you find the same error, I believe it’s safe to continue.

Once Eclipse has restarted and Mercurial has been installed, you can import project code straight from google code into Eclipse.  To import the AndEngine source code, go to File -> Import, select the new option labeled Mercurial folder, and click “Clone Existing Mercurial Repository.”  From there, enter “” in the URL box, and it will make a clone of the code in your eclipse workspace.  After a short wait, it will ask you to select a working directory revision- select default, then press “finish” on the next screen to complete the copying process.  There you have it- the AndEngine code is now located on your computer!  It may show some errors- that’s normal, though hopefully within a few weeks it’ll be fixed.

If you’ve followed me up to this point, you should have a new project named AndEngine in your workspace directory.  Nicely done!  Now you need some examples of code so you can see how the engine works, as well as some plugins.  Go ahead and run Mercurial again, with the following Mercurial address: “”

NOTE: As of right now, the AndEngineExamples have a few errors in the default configuration.  To fix this, download the AndEngine code by performing the same process using Mercurial with the following addresses:

Sometimes, an error occurs where Eclipse won’t compile the project if a folder is missing; if this happens, simply find your workspace directory and create the folder manually, then close and re-open Eclipse.  It should resolve any remaining errors.  Also, in my project, one of the examples was reporting an error- making it an empty activity made everything compile and run simply!  

User Francis has pointed out one way to increase compatibility: 
Goto Project/Properties/Java Compiler and set the Compiler compliance level to at least 1.6.  This definitely helps.  Thanks!

Once you get the AndEngineExamples code working, you will find that there are two important parts of this project:

(1) The examples.  Almost anything you need to know about AndEngine is covered in the examples here: over the next few posts, I’ll go over a few of the most common ones, but if you want to explore them yourself, by all means, dive in!  At very least, compile the project and check out a few of the examples in action.

(2) The Source Code.  If you followed the instructions in the note above, you will now have the code as a separate project.  Congratulations- you should now be able to both view the AndEngine code and import it into any project in your workspace!

So, there you have it- you now have everything you need to begin coding with AndEngine!  Stay tuned, and we’ll take a look at how to make projects that will leave you the star of the Android Market!

Up Next: Getting Started: The Work Order of AndEngine