You are Here:Home>>Old Posts>>Using Box2DFlashAS3 (AS3 physics engine) Part 2 – Basic example

Using Box2DFlashAS3 (AS3 physics engine) Part 2 – Basic example

By | 2009-05-09T15:22:05+00:00 May 9, 2009|Old Posts|

In recent tutorial, you learn some basic things which are important before start to use Box2DFlashAS3. In the following tutorial. I will teach you with example to use a basic world.

In the following tutorial, you will learn how to setup a basic scene – one ball and one box hit the ground. When running the flash, you will see the ball and box fall and bound off the ground.

A. Setup the scene graphics.

First, we need to setup the graphics we needed for simulation.

1. Open a new Action script 3.0 project in flash.

2. Draw and ground with box tool. I set it to 500 width x 50 height.

3. Convert it to a movie clip (press F8).

4. Name it with instance name “ground_mc”.

5. Double click and edit it. Place it center to origin (0,0).

6. Draw a ball (60 x 60). Name it with instance name “ball_mc”. Repeat step 2 to 5.

7. Draw a box (40 x 40). Name it with instance name “box_mc”. Repeat step 2 to 5.

8. Position the graphics like show below.

box2d_2_fig_2

B. Adding Action Script

Step 1. Select the frame on the timeline and open the actionscript panel(F9 or option+F9 in mac).

box2d_2_fig_3

Step 2. Enter the code below to import necessary library.

// Classes used in this example
import Box2D.Dynamics.*;
import Box2D.Collision.*;
import Box2D.Collision.Shapes.*;
import Box2D.Common.Math.*;

Step 3. Enter the code below to set the constant

// Define constant
var m_iterations:int = 5; // define the iteration of simulation
var m_timeStep:Number = 1.0/5.0; //define the time step of simulation

Step 3. Construct world object for simulation

The world object is use to define a world like the real world. You will have gravity inside. All object will add to this world object for simulation.

// Creat world AABB
var worldAABB:b2AABB = new b2AABB();
worldAABB.lowerBound.Set(-100.0, -100.0);
worldAABB.upperBound.Set(1000.0, 1000.0);

// Define the gravity vector
var gravity:b2Vec2 = new b2Vec2(0.0, 10.0);

// Construct a world object
var world:b2World = new b2World(worldAABB, gravity, true);

Step 4. Setup the ground object

A ground object is just like the ground in the real world. It is static and allow other object to collis on it without moving.

First, we need to define the properties of the ground. We use a b2PolygonDef to define the physical properties and b2BodyDef to define the simulation properties. It is important to set the property “density” to 0. Since 0 value means the ground is non-movable object.

To set the size of the shape, we use the SetAsBox function. The SetAsBox function takes the half-width and half-height. So in this case the ground box is 100 units wide (x-axis) and 20 units tall (y-axis).

The object b2PolygonDef also use to define the physical properties of the object.

friction – Friction is used to make objects slide along each other realistically
restitution – Restitution is used to make objects bounce.
density – The density of the object

I will talk more about these proprties in the future tutorials.

// Construct a shape definition for the ground
// It is use to store the physical properties of the ground
var groundDefinition:b2PolygonDef = new b2PolygonDef();
groundDefinition.SetAsBox(250, 25);
groundDefinition.friction = 0.3;
groundDefinition.density = 0; // we set the density to 0 means the ground is not movable

// Construct a body definition for the ground
// It is use to store the position and rotation of the ground
var groundBodyDefinition:b2BodyDef = new b2BodyDef();
groundBodyDefinition.userData = ground_mc; // Link to the visualize object named “ground_mc”
groundBodyDefinition.position.Set(ground_mc.x, ground_mc.y);
groundBodyDefinition.angle = ground_mc.rotation/180*Math.PI;

Then, we will use the body definition to create a body object for simulation. Then we creating the ground polygon shape on the ground body.

// Construct a body object and add to the world object for simulation
var groundBody:b2Body = world.CreateBody(groundBodyDefinition);
groundBody.CreateShape(groundDefinition);
groundBody.SetMassFromShapes();

Step 5. Setup the ball for simulation

Now, we setup the ball object. It is similar to the setup of the ground. But we use b2CircleDef as the shape definition object. Since it is a circle like object. We can set the radius of the shape.

// Construct a shape definition for the ball
// It is use to store the physical properties of the ball
var ballDefinition = new b2CircleDef();
ballDefinition.radius = 30;
ballDefinition.density = 3.0;
ballDefinition.friction = 0.5;
ballDefinition.restitution = 1; // We set the restitution properties to control the bounce of the object. Higher means more elastic

// Construct a body definition for the ball
// It is use to store the position and rotation of the ball
var ballBodyDefinition:b2BodyDef = new b2BodyDef();
ballBodyDefinition.userData = ball_mc;
ballBodyDefinition.position.Set(ball_mc.x, ball_mc.y);
ballBodyDefinition.angle = ball_mc.rotation/180*Math.PI;

// Construct a body object and add to the world object for simulation
var ballBody:b2Body = world.CreateBody(ballBodyDefinition);
ballBody.CreateShape(ballDefinition);
ballBody.SetMassFromShapes();

Step 6. Setup the box for simulation

We setup the box object by the code below.

// Construct a shape definition for the box
// It is use to store the physical properties of the box
var boxDefinition = new b2PolygonDef();
boxDefinition.SetAsBox(20, 20);
boxDefinition.density = 1.0;
boxDefinition.friction = 0.5;
boxDefinition.restitution = .5;

// Construct a body definition for the box
// It is use to store the position and rotation of the box
var boxBodyDefinition:b2BodyDef = new b2BodyDef();
boxBodyDefinition.userData = box_mc;
boxBodyDefinition.position.Set(box_mc.x, box_mc.y);
boxBodyDefinition.angle = box_mc.rotation/180*Math.PI;

// Construct a body object and add to the world object for simulation
var boxBody:b2Body = world.CreateBody(boxBodyDefinition);
boxBody.CreateShape(boxDefinition);
boxBody.SetMassFromShapes();

Step 7. Setup the render loop

Last, we need to setup a render loop to calculate the simulation result. Then, assign the new simulation result to the object.

function render(e:Event):void
{

// calulate the simulation
world.Step(m_timeStep, m_iterations);

// Go through body list and update sprite positions/rotations
for (var bb:b2Body = world.m_bodyList; bb; bb = bb.m_next){
if (bb.m_userData is Sprite){
bb.m_userData.x = bb.GetPosition().x;
bb.m_userData.y = bb.GetPosition().y;
bb.m_userData.rotation = bb.GetAngle() * (180/Math.PI);
}
}
}

// Add the Event.ENTER_FRAME listener
addEventListener(Event.ENTER_FRAME,render);

That all for the code in this example, you can test the movie. You will see the ball and box falling and hit the ground. The ball bounce more due to a higher restitution value.

box2d_2_fig_4

You can download the source code here for testing (right click and save as zip file). Since the file not included the Box2D library. You need to download it from here or follow the previous tutorial to setup your working environment first.

In this tutorials, you just learn to setup a basic world for simulation. In next tutorial, i will talk about each advanced features.

About the Author:

A father, a husband and a geek... Biitlog Founder, The Tech Labs founder, among other projects.

11 Comments

  1. Anonimo May 9, 2009 at 5:36 pm - Reply

    var ballDefinition:????? = new b2CircleDef();

  2. Anonimo May 9, 2009 at 6:23 pm - Reply

    crazy for the next tutorial =)

  3. WaiLam May 10, 2009 at 9:56 am - Reply

    For strict should be

    var ballDefinition:b2CircleDef = new b2CircleDef();

  4. Midnyt May 13, 2009 at 3:30 pm - Reply

    Your source code link is to a jpg image that doesn’t work. Can you fix that please? Thanks!

    I love the tutorials, these and the character animation with bones. Keep them coming!

  5. WaiLam May 14, 2009 at 10:18 am - Reply

    You need to right click on the link and save it to a .zip file.

  6. noobie May 18, 2009 at 2:41 pm - Reply

    Great, need the next tutorial !

  7. noobie May 19, 2009 at 3:18 pm - Reply

    Description:
    1119: Accès à la propriété x peut-être non définie, via la référence de type static Class.

    Source:
    groundBodyDefinition.position.Set(ground_mc.x, ground_mc.y);

    Can you help me please ?

  8. noobie May 19, 2009 at 3:28 pm - Reply

    Problem resolved. 🙂

  9. muzn July 15, 2009 at 12:28 am - Reply

    From that code, are you able to improvise it in such a way that able to drag and drop. Im trying to work on it but it doesnt work………..

  10. WaiLam July 16, 2009 at 4:13 am - Reply

    >> muzn

    You can try to lookat the example download from Box2DAS3.

    in the file TestBed/test.as , MouseDrag() function…

    You can find the answer for how to to with a mouse drag.

  11. Misiur March 21, 2010 at 4:38 pm - Reply

    Well, noone told me that i need Flash CS4 ; ) (I mean, i can’t use Flash Player 10 in CS3 [only tricks])

Leave a Reply