AndEngine Sprites, Physics and Touch

Guides | Tutorial By 4 years ago

Last time we set up your Android/AndEngine dev. environment, now we’re gonna get a Sprite up on screen and make it react to touch events and physics.

First things first, let’s open up that project from last time, and change our background colour from that blinding red.

Change the line:

mScene.setBackground(new Background(1, 0, 0));


mScene.setBackground(new Background(1, 1, 1));

Which will give us a nice solid white instead. If you want, boot up your AVD and have a look.

Now we want to create a new Sprite, so create a new member variable called mSprite.

Sprite mSprite

We’ll have to import the Sprite class now to get rid of that nasty red line. Now, in onCreateScene we want to initialise our Sprite and add it to the scene- but to do that we’re going to need a graphic for the sprite. Here’s one I prepared earlier:

It’s a pretty bangin’ rock. Feel free to use that graphic. If you’re going to use your own, make sure it’s 64×64, or that you change the Texture Atlas initialization code to suite your individual image. Speaking of Texture Atlas initialization code, we’re going to have to load up that image now. Place the image in your assets/gfx/ directory within your project. We’re going to have to add the following new variables for the initialization of our textures:

BitmapTextureAtlas mBitmapTextureAtlas;
ITextureRegion mRockTex;

Now we want to go down to our onCreateResources() function and add in the lines from below, which set the path for graphics assets, load up our texture atlas, and load our texture into the atlas and give us a reference to it.

protected void onCreateResources()
  mBitmapTextureAtlas = new BitmapTextureAtlas(getTextureManager(), 64, 64);

  mRockTex = BitmapTextureAtlasTextureRegionFactory.createFromAsset(mBitmapTextureAtlas, this, "rock.png", 0, 0);

The texture atlas is initialized to fit all the textures you want in it, so in this case it’s 64×64 as our rock image is 64×64. If I wanted two textures that were 64×64 I’d initialize the texture atlas as 128×64 and then load the second texture with 64, 0 as the location in the atlas to place it, rather than 0, 0.

Now we’ve got that we can load up our first basic Sprite, by adding these lines of code to the onCreateScene() function:

mSprite = new Sprite(0, 0, mRockTex, getVertexBufferObjectManager());

Those two lines will create our sprite using the mRockTex we loaded, place it in the top left of the screen (0, 0) and attach it to our scene, allowing it to be updated and drawn. If you run your app now you should see the picture of the rock in the top left.

Next up, we’re gonna create a new class called “Flingable”. This Flingable is going to be our special Sprite, that we will be able to fling across the screen in an “Angry Birds”-esque fashion. You can create a new class by going to the same place your MainActivity.class file is, right-clicking on it, and going New -> Class which will bring up a New Class creation window. All we want is to type in the name “Flingable” and hit Finish. Now you should see something like this:

package b2cloud.tutorial.andenginetest;

public class Flingable {


After that we want to change the line:

public class Flingable


public class Flingable extends Sprite

To make our Flingable inherit all the fancy jazz from Sprite.

Now mouse over the error on Sprite and import the Sprite class, and then add this constructor to the Flingable class.

public Flingable(float pX, float pY, ITextureRegion pTextureRegion,
			VertexBufferObjectManager pVertexBufferObjectManager) {
		super(pX, pY, pWidth, pHeight, pTextureRegion, pVertexBufferObjectManager);
		// TODO Auto-generated constructor stub

Now we’ve got our class basics set up, we need to add some physics to our sprite, as a flingable sprite is prone to the laws of physics. For this, we’ll use AndEngine’s basic “PhysicsHandler” class. We’re going to need one of these in Flingable, so add a new member of that type, as well as some floats we can use as reference points to where we started (and what we have to fling through):

private PhysicsHandler mPhysicsHandler;
private float originX, originY;

And initialise them in the constructor:

mPhysicsHandler = new PhysicsHandler(this);

originX = pX;
originY = pY;

Where the argument “this” indicates the entity for which the PhysicsHandler… handles physics 🙂
We also want to register our physics handler so it receives updates, and initialise our originX and Y for flinging.

Now we want to add some behaviour on touch, so we need to override the onAreaTouched function, like so: (and make sure you import TouchEvent)

public boolean onAreaTouched(final TouchEvent pSceneTouchEvent, final float pTouchAreaLocalX, final float pTouchAreaLocalY)
  return true;

This is where we’ll add the code that makes our Flingable, flingable. 🙂
In the touch handler you get access to a few things, including the co-ordinates of the touch in both the local and scene space, as well as the kind of touch (Down, Up, Move, Outside) we’re going to use these to make the rock drag to the player’s finger, and then when the player releases, the rock should fling away.

if (pSceneTouchEvent.isActionMove() || pSceneTouchEvent.isActionDown() || pSceneTouchEvent.isActionOutside())
	this.setX(pSceneTouchEvent.getX() - this.getWidth() / 2);
	this.setY(pSceneTouchEvent.getY() - this.getHeight() / 2);
else if (pSceneTouchEvent.isActionUp())
	mPhysicsHandler.setVelocityX((originX - getX()) * 5);
	mPhysicsHandler.setVelocityY((originY - getY()) * 5);

This checks the action and if it is a move/drag/down action (including if the players finger moves outside the sprite) it moves the sprite to that point. Otherwise, if the player has removed their finger, it sets the velocity as 5 times the difference between the current position and the origin position (thus making the sprite fling through the origin point) and sets the Y acceleration to add gravity. Playing with these variables will change the feel of the flinging action, make the rock feel heavier or lighter, or the ‘elastic’ more springy.

Now, we should be able to just change our sprite in our MainActivity to a flingable and away we go:

Flingable mSprite;

and then in onCreateScene:

mSprite = new Flingable(300, 300, mRockTex, getVertexBufferObjectManager());

Note that we now have register the touch area with the scene so that it actually checks if the entity has been touched and executes our touch code. I’ve also moved my sprite closer to the middle of the screen to make it easier to fling around. Check out the video below for what it looks like.