Keyboard controlled bodies in Box2D AS3

From Box2D Wiki

In this article, I will explain how to create a body that can be controlled by Keyboard input, in Box2D AS3. 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

The easiest way to control the motion of a body in Box2D is to apply forces or impulses to it. When we want to control a body using the keyboard we need to apply those forces when some key triggers them. In this example we will create a scenario where we control the motion of a circular object using the arrow keys on the keyboard.

First we create a circular object in our world.

//A world has been created, in variable myWorld. 
var myWorld:b2World;
 
// define our shape
var boxDef:b2CircleDef = new b2CircleDef();
boxDef.radius = 2 
boxDef.friction = 0.3
boxDef.density = 1;
 
// define our body
var bodyDef:b2BodyDef = new b2BodyDef();
bodyDef.linearDamping = 10
bodyDef.position.Set(9, 10) 
 
// Add our body to the world
var myBody:b2Body = myWorld.CreateBody(bodyDef);
myBody.CreateShape(boxDef);
myBody.SetMassFromShapes();

Now we create an EventListener that will listen to keyboard events and apply the right force to our circular object.

stage.addEventListener(KeyboardEvent.KEY_DOWN, keyPressed_handler);
 
function keyPressed_handler(e:KeyboardEvent){
  //Direction is a vector that will be applied as an impulse to our object.
  var direction:b2Vec2 = new b2Vec2();
 
  //The value of direction is determined by the key that the user pressed.
  switch(e.keyCode){
    case Keyboard.DOWN:
    direction.Set(0,200);
    break;
    case Keyboard.UP:
    direction.Set(0,-200);
    break;
    case Keyboard.LEFT:
    direction.Set(-200,0);
    break;
    case Keyboard.RIGHT:
    direction.Set(200,0);
    break;
  }
 
  //Finally, we wake up the object and apply an impulse.
  body.WakeUp();
  body.ApplyImpulse(direction, body.GetPosition());
}
Image:Icon-tutorials.png‎ Tutorials

General

AS3

TOOLBOX
LANGUAGES