Linking graphics to bodies in Box2D AS3

From Box2D Wiki

This article is meant to offer some help when you are trying to represent objects in Box2D with Flash Sprites or MovieClips to them. I will assume that you know how to create a world, and create physics bodies inside of it. Take a look at the Manual if you don't.

Method

Box2D will only handle the physics calculations of your application, it does not handle skinning, but it can provide the location and rotation of each object at every frame. Using this information, we can move our graphics to the right location.

A simple way of syncing up our graphics with a Box2D world would be the following.

//A world has been created, in variable myWorld. 
var myWorld:b2World;
 
//A body has been added to the world, as variable myBody.
var myBody:b2Body;
 
//Some kind of sprite or movieclip has been added to the stage, as myGraphic.
var myGraphic:DisplayObject;
 
//Because Box2D works with MKS scale, 1 pixel should not map directly to 1 Box2D Unit,
// that is why we use a physics scale.
var physScale:Number = 30;
 
//The following code is executed every frame, along with b2World.Step().
function moveBody(){
    var bodyPosition:b2Vec2 = myBody.GetPosition();
    var bodyRotation:Number = myBody.GetAngle();
    myGraphic.x = bodyPosition.x * physScale;
    myGraphic.y = bodyPosition.y * physScale;
    myGraphic.rotation = bodyRotation  * (180/Math.PI) % 360; //Don't forget to convert to degrees!
}

A different approach

The method mentioned above results in the sprite position being slightly off from the actual position of the box. If you use a large scaling constant it probably isn't an issue, but if you use a small constant you should use the more technically correct version, show below to position your sprite:

//The following code is executed every frame, along with b2World.Step().
function moveBody(){
 
    // World state position
    var bodyPosition:b2Vec2 = myBody.GetPosition();
    var bodyRotation:Number = myBody.GetAngle();
 
    // Sprite rotation based (0,0) correct for size by moving sprite before rotation.
    // ie. rotation about the center of the sprite.
    myGraphic.rotation = 0; // If not, matrix starts wrong.
    var m:Matrix = myGraphic.transform.matrix;
    m.identity();
    m.tx = -myGraphic.width / 2 ;
    m.ty = -myGraphic.height / 2;
    m.rotate(bodyRotation); // Already in radians
 
    // Now set the position to the world position
    m.tx += bodyPosition.x * physScale;
    m.ty += bodyPosition.y * physScale;
 
    // ...and set the whole thing at once via the matrix.
    // ie. Update the sprite.
    myGraphic.transform.matrix = m;
}

A Better Approach

While the previous approach works well enough, it requires that you keep specific variables for each of your DisplayObjects and bodies. A more scalable approach is to create Actor objects, that function as links between bodies and graphics. Below is a simple actor class.

public class Actor {
    public var body:b2Body;
    public var graphic:DisplayObject;
 
    public function Actor(b:b2Body, g:DisplayObject){
        body = b;
        graphic = g;
    }
 
    public function updatePosition():void {
	var bodyPosition:b2Vec2 = body.GetPosition();
	var bodyRotation:Number = body.GetAngle();
	var matrix:Matrix = graphic.transform.matrix;
 
        // Sprite rotation based (0,0) correct for size by moving sprite before rotation.
        // ie. rotation about the center of the sprite.
	graphic.rotation = 0;// If not, matrix starts wrong.
 
	matrix.tx = -graphic.width / 2;
	matrix.ty = -graphic.height / 2;
	//rotate
	matrix.rotate(bodyRotation);// Already in radians
	//move to the world position
	matrix.tx += bodyPosition.x * scale;
	matrix.ty += bodyPosition.y * scale;
 
	graphic.transform.matrix = matrix;
 
    }
}

Now you create an actor every time you create a body, and you add both the body and the graphic to this actor. You can also assign the actor to the userData of the body, so that you can link the actor to the body's event. Then you can create a list of actors, and iterate through this list, updating the positions and rotations of each of your graphics.

//Initialize an array that will hold all actors.
var allActors:Array = new Array();
 
//Create a new actor for our body
var myActor:Actor = new Actor(myBody, myGraphic);
myBody.m_userData = myActor;
 
//Add our body to the stack.
allActors.push(myActor);
 
//This function can now be called each frame, and it will update the position of all graphics but it still need to work with step.
function on_enter_frame(e:Event) {
    for each (var a:Actor in allActors) {
 
        //we call the actor's method
        a.updatePosition();
    }
}
Image:Icon-tutorials.png‎ Tutorials

General

AS3

TOOLBOX
LANGUAGES