Some Physics functions in AndEngine GLES1.0 + Box2D

AndEngine is one of the best game engines available to build 2D games on the Android platform. It has a load of great features, one of which its integration with the Box2D physics engine. This is done via a great extension.

There are many sources out there to help developers with integrating physics features in to AndEngine, including examples from the author of the engine himself, however, I thought of writing my own helpful guide with some of the lesser-explained functions of AndEngine’s physics engine.

You’ll be able to use this awesome blog post by Maya Posch to set up AndEngine and get it configured with the AndEngine Physics Box2D Extension. It’s a bit complicated, so if you’re lazy like me you could find the compiled sources from the previously-linked Examples repository (though this is NOT recommended).

Now, to get started on some of the functions that you’ll need. The Box2D environment, when oversimplified, contains the following main elements:

  • Physics World: This is where all the exciting business goes on, and where all the elements related to physics are stored and manipulated. Welcome to the world of physics!
  • Bodies: Bodies are similar to sprites in any game; they’re what move about, crash in to each other etc.
  • Vectors: These are what you’ll be applying on your bodies (you do know your basic physics, right?) to make them move around, rotate, stop, and every other conceivable thing.

Basics aside, we’ll look at a few functionalities that are rarely explained in most AndEngine physics examples:

  1. Contact Listeners:

Contact listeners are Box2D’s equivalent to collision detection in game engines. A ContactListener is defined for the Physics World in general, and will handle all contacts that happens in that world. That means, when a contact listener fires, you’ll only get the Fixtures (and underlying Bodies) of that particular contact to manipulate. Handling contact listeners in this way can get pretty dirty pretty fast, it turns in to a mess of checking fixtures for their underlying attributes and rechecking to see if they’re the actual body within the physics world that you want to check for collisions. Well, you did want to have smooth physics in your game, right? Now pay the price. 😉

Following is a code snippet from a car racing game I worked on:

mPhysicsWorld.setContactListener(new ContactListener() {

			public void preSolve(Contact contact, Manifold oldManifold) {

			}

			public void postSolve(Contact contact, ContactImpulse impulse) {

			}

			public void endContact(Contact contact) {

			}

			public void beginContact(Contact contact) {

				if ( contact.getFixtureA().getBody().getUserData() != null &&
						contact.getFixtureB().getBody().getUserData() != null  ) {
                                        //I stored a 'Car' object in the userdata of each physics body as I created it
					final Car carA = (Car)contact.getFixtureA().getBody().getUserData();
					final Car carB = (Car)contact.getFixtureB().getBody().getUserData();
					if ( carA.getId() == 1 || carB.getId() == 1 ) {
						carState = CAR_STATE_CRASHED;
						vibrator.vibrate(100);
                                        }
                                }
                      }
});

By returning the bodies associated with each fixture in teh contact, I have managed to get the ‘Car’ type objects stored within the userdata elements within each body. By checking a specific value within these car objects, I have decided what to do next. Any contact handling that you’d do with AndEngine + Box2D would have to be a lot of if-else clauses where you check whether the bodies crashing together within the physics world are the bodies you want to check for collisions with. The presolve() an postsolve() methods are concerned with preparing the physics world for the contact, where you can set various attributes like whether contacts are enabled at that point.

2. Setting your body’s velocity to 0:

This might seem like a weird requirement, but believe me, after your sprites start bouncing around the screen like crazy ping pong balls, you’ll thank me. This is something it took me a while to figure out, so I thought I’d share:

Vector2 linearZero = Vector2Pool.obtain(0,0);
playerBody.setLinearVelocity(linearZero);
Vector2Pool.recycle(linearZero);//don't forget to recycle your vectors! It helps save the environment.

Ok, so you have your playerBody right? What you do is, you initialize a vector with 0 values, and you apply that as the linear velocity to your body. That will stop the body from moving on all plains.

3. Insta-move your sprite to any place on the screen:

Sometimes, even when you have a physics engine at your disposal, you just want to magically materialize your sprite somewhere on the screen. The problem is, if you use the normal AndEngine sprite.setPosition() method, the physics body you’ve attached to the sprite is not going to move with it. You need to use Box2D itself to insta-move your sprite (once you move the body, the sprite will always move with it, but not vice-versa):

 

Vector2 transformVector = Vector2Pool.obtain(newXPosition, newYPosition);
playerBody.setTransform(transformVector, playerBody.getAngle());
Vector2Pool.recycle(transformVector);

Vectors again. Simply build a new vector containing the X and Y coordinates you want to move your sprite to, and use the setTransform() method on the body attached to the sprite.

 

That’s it from me for now. More soon!