Advertisement
  1. Code
  2. Coding Fundamentals
  3. Game Development

Introduction to Box2D for Flash and AS3

Scroll to top

Box2D is a popular physics engine with a solid Flash port, which was used to create the excellent game Fantastic Contraption. In this tutorial, the first of a series, you'll get to grips with the basics of Box2D 2.1a for Flash and AS3.


Step 1: The Boring Setup

I'm going to assume you already know how to set up a basic Flash project using your editor and workflow of choice, whether that means creating a FLA with a document class, a pure AS3 project in a different editor, or whatever. I'm using FlashDevelop, but you should use whatever you feel comfortable with.

Create your project, and name the main class Main.as. Give it some boilerplate code; mine looks like this:

1
2
package 
3
{
4
	import flash.display.Sprite;
5
	import flash.events.Event;
6
7
	[Frame(factoryClass="Preloader")]
8
	public class Main extends Sprite 
9
	{
10
11
		public function Main():void 
12
		{
13
			if (stage) init();
14
			else addEventListener(Event.ADDED_TO_STAGE, init);
15
		}
16
17
		private function init(e:Event = null):void 
18
		{
19
			removeEventListener(Event.ADDED_TO_STAGE, init);
20
			getStarted();
21
		}
22
		
23
		private function getStarted():void
24
		{
25
			
26
		}
27
28
	}
29
30
}

Don't worry about the [Frame] metatag -- that's just how FlashDevelop creates a preloader. All you need to know is that getStarted() is run when the SWF has fully loaded. Create a function of the same name that runs when your Main class has loaded.

I'm also going to assume you're comfortable with using a separate library or API in your project. Download Box2DFlash 2.1a from this page (I'm using the Flash 9 version), and extract the zip to wherever you normally put your APIs. Next, add a classpath to point to the \Source\ folder from the zip. Alternatively, you could just extract the contents of the \Source\ folder to the same directory as your Main class.

Great! That was easy. Let's start using Box2D.


Step 2: A Whole New b2World

"If you want to make an apple pie from scratch, you must first create the universe," wrote Carl Sagan; if we want to make a few physics objects, we only need to create a world.

In Box2D, a world is not a planet or an ecosystem; it's just the name given for the object that manages the overall physics simulation. It also sets the strength of gravity -- not just how quickly objects accelerate but also in which direction they fall.

We'll create a vector to set the gravity before creating the world itself:

1
2
import Box2D.Common.Math.b2Vec2;
3
4
//...

5
6
private function getStarted():void
7
{
8
	var gravity:b2Vec2 = new b2Vec2(0, 10);
9
}

A b2Vec2 is a Box2D Euclidean vector (the second 2 stands for 2D again, because it's possible to have a 3D Euclidean vector). Daniel Sidhion wrote an excellent tutorial explaining what Euclidean vectors are (they are nothing to do with the Vector class in AS3), so check that out if you're not sure. But briefly, think of a Euclidean vector as an arrow:

This arrow shows b2Vec2(4, 9); it points down and to the right. Our gravity vector, then, will point straight down. The longer the arrow, the stronger the gravity, so later on in the tutorial you could try changing the gravity vector to b2Vec(0, 2) to simulate a much weaker gravity, much like that on the Moon.

Now we'll create the world itself:

1
2
import Box2D.Dynamics.b2World;
3
4
//...

5
6
public var world:b2World;
7
8
//...

9
10
private function getStarted():void
11
{
12
	var gravity:b2Vec2 = new b2Vec2(0, 10);
13
	world = new b2World(gravity, true);
14
}

The second parameter we pass to b2World() tells it that it can stop simulating objects that it doesn't need to simulate any more, which helps speed up the simulation but is completely irrelevant to us at the moment.

Run the SWF to check there are no errors. You won't be able to see anything yet, though. The world is currently completely empty!


Step 3: Reinvent the Wheel

Let's create a simple circular object; this could represent a rock, a basketball, or a potato, but I'm going to see it as a wheel.

I'd love to say that doing this is as simple as:

1
2
var wheel:b2CircularObject = new b2CircularObject();

...but that would be a big fat lie. The thing about Box2D is, apparently simple things can require quite a bit of code to get sorted. This extra complexity is very useful for doing advanced work, but it kinda gets in our way for simple things like what we're trying to do at the moment. I'm going to quickly go over what we need to do to make this wheel; we can examine it in more detail in later tutorials.

To create a single "physics object" -- that is, an object with a shape and a mass that Box2D can simulate within a world -- we must construct it using five different classes:

  • A body definition, which is like a template for creating...
  • A body, which has a mass and a position, but doesn't have...
  • A shape, which could be as simple as a circle, that must be connected to a body using...
  • A fixture, which is created using...
  • A fixture definition which is another template, like the body definition.

Phew. Here's what that all looks like in code:

1
2
import Box2D.Dynamics.b2BodyDef;
3
import Box2D.Dynamics.b2Body;
4
import Box2D.Collision.Shapes.b2CircleShape;
5
import Box2D.Dynamics.b2Fixture;
6
import Box2D.Dynamics.b2FixtureDef;
7
8
//...

9
10
private function getStarted():void
11
{
12
	var gravity:b2Vec2 = new b2Vec2(0, 10);
13
	world = new b2World(gravity, true);
14
	
15
	var wheelBodyDef:b2BodyDef = new b2BodyDef();
16
	var wheelBody:b2Body = world.CreateBody(wheelBodyDef);
17
	var circleShape:b2CircleShape = new b2CircleShape(5);
18
	var wheelFixtureDef:b2FixtureDef = new b2FixtureDef();
19
	wheelFixtureDef.shape = circleShape;
20
	var wheelFixture:b2Fixture = wheelBody.CreateFixture(wheelFixtureDef);
21
}

The argument that we pass to b2CircleShape() specifies the radius of the circle. Everything else should make sense based on the list above, even if the reasoning behind this structure makes no sense.

Note that we never write new b2Body() or new b2Fixture(); the world is used to create the body from the body definition, and the body is used to create the fixture from the fixture definition. This means that the world knows about all the bodies that are created within it, and the body knows about all the fixtures that are created that connect shapes to it.

The actual physics object that we've created is the wheelBody; everything else is just part of a recipe to form that one object. So, to check that we've been successful, let's see whether the wheelBody exists:

1
2
private function getStarted():void
3
{
4
	var gravity:b2Vec2 = new b2Vec2(0, 10);
5
	world = new b2World(gravity, true);
6
	
7
	var wheelBodyDef:b2BodyDef = new b2BodyDef();
8
	var wheelBody:b2Body = world.CreateBody(wheelBodyDef);
9
	var circleShape:b2CircleShape = new b2CircleShape(5);
10
	var wheelFixtureDef:b2FixtureDef = new b2FixtureDef();
11
	wheelFixtureDef.shape = circleShape;
12
	var wheelFixture:b2Fixture = wheelBody.CreateFixture(wheelFixtureDef);
13
	
14
	trace(wheelBody);
15
}

Result:

1
2
[object b2Body]

Good.


Step 4: Move Your Body

Do you know what I mean when I talk about the "game loop" and a "tick"? If not, go read my short article, Understanding the Game Loop, right now, because it's really important for what we're doing.

The Box2D world object has a method, Step(), which drives the simulation. You specify a tiny period of time (a fraction of a second), and Step() simulates the movement and collisions of every object in the world; once the function has run, all the body objects will have been updated with their new positions.

Let's see this in action. Instead of tracing wheelBody itself, we'll trace its position. Then, we'll run b2World.Step(), and trace the wheel's position again:

1
2
private function getStarted():void
3
{
4
	var gravity:b2Vec2 = new b2Vec2(0, 10);
5
	world = new b2World(gravity, true);
6
	
7
	var wheelBodyDef:b2BodyDef = new b2BodyDef();
8
	var wheelBody:b2Body = world.CreateBody(wheelBodyDef);
9
	var circleShape:b2CircleShape = new b2CircleShape(5);
10
	var wheelFixtureDef:b2FixtureDef = new b2FixtureDef();
11
	wheelFixtureDef.shape = circleShape;
12
	var wheelFixture:b2Fixture = wheelBody.CreateFixture(wheelFixtureDef);
13
	
14
	trace(wheelBody.GetPosition().x, wheelBody.GetPosition().y);
15
	world.Step(0.025, 10, 10);
16
	trace(wheelBody.GetPosition().x, wheelBody.GetPosition().y);
17
}

(The GetPosition() method of a body returns a b2Vec2, so we need to trace the individual x and y properties rather than just calling trace(wheelBody.GetPosition().)

The first parameter we pass to Step() is the number of seconds to simulate passing in the Box2D world. The other two parameters specify how much accuracy Box2D should use in all the mathematical calculations it uses to simulate the passing of time. Don't worry about these right now; just know that bigger numbers could make Box2D take more time to simulate the world -- if you set these too high, it might even take longer than 0.025 seconds to run Step(), so we'd be getting out of sync with the real world!

Test the SWF, and look at your output window:

1
2
0 0
3
0 0

That's a little depressing. The wheel hasn't moved at all -- and yet, the world has gravity, so you'd think it would have fallen a little bit. What's going on?


Step 5: Being Dynamic

By default, all Box2D bodies are static, meaning that they don't move. Think of the actual platforms in a platform game; they're solid objects, but aren't affected by gravity and can't be pushed around.

We need our wheel to be dynamic, so that it can move. Guess how we define this property of the body? Using the body definition, of course!

1
2
private function getStarted():void
3
{
4
	var gravity:b2Vec2 = new b2Vec2(0, 10);
5
	world = new b2World(gravity, true);
6
	
7
	var wheelBodyDef:b2BodyDef = new b2BodyDef();
8
	wheelBodyDef.type = b2Body.b2_dynamicBody;
9
	var wheelBody:b2Body = world.CreateBody(wheelBodyDef);
10
	var circleShape:b2CircleShape = new b2CircleShape(5);
11
	var wheelFixtureDef:b2FixtureDef = new b2FixtureDef();
12
	wheelFixtureDef.shape = circleShape;
13
	var wheelFixture:b2Fixture = wheelBody.CreateFixture(wheelFixtureDef);
14
	
15
	trace(wheelBody.GetPosition().x, wheelBody.GetPosition().y);
16
	world.Step(0.025, 10, 10);
17
	trace(wheelBody.GetPosition().x, wheelBody.GetPosition().y);
18
}

Try the SWF now, and see what you get:

1
2
0 0
3
0 0.00625

It's moved! How exciting!


Step 6: Keep on Moving

We can't call this a game loop yet, though, because it's only running once; we need it to run over and over and over again. We can make this happen using a Timer and an event listener:

1
2
import flash.utils.Timer;
3
import flash.events.TimerEvent;
4
5
//...

6
7
private function getStarted():void
8
{
9
	var gravity:b2Vec2 = new b2Vec2(0, 10);
10
	world = new b2World(gravity, true);
11
	
12
	var wheelBodyDef:b2BodyDef = new b2BodyDef();
13
	wheelBodyDef.type = b2Body.b2_dynamicBody;
14
	var wheelBody:b2Body = world.CreateBody(wheelBodyDef);
15
	var circleShape:b2CircleShape = new b2CircleShape(5);
16
	var wheelFixtureDef:b2FixtureDef = new b2FixtureDef();
17
	wheelFixtureDef.shape = circleShape;
18
	var wheelFixture:b2Fixture = wheelBody.CreateFixture(wheelFixtureDef);
19
	
20
	var stepTimer:Timer = new Timer(0.025 * 1000);
21
	stepTimer.addEventListener(TimerEvent.TIMER, onTick);
22
	trace(wheelBody.GetPosition().x, wheelBody.GetPosition().y);
23
	stepTimer.start();
24
}
25
26
private function onTick(a_event:TimerEvent):void
27
{
28
	world.Step(0.025, 10, 10);
29
	trace(wheelBody.GetPosition().x, wheelBody.GetPosition().y);
30
}

(Note that I've given the timer a period of 0.025 seconds as well, so that it stays in sync with the world's steps. You don't have to do this -- in fact, if you make the two periods different, you can get some really cool time-related effects, like slow-motion.)

But, oops, that code won't work; we need wheelBody to be accessible in the onTick() function. While we're at it, we might as well make the timer accessible everywhere, too:

1
2
public var world:b2World;
3
public var wheelBody:b2Body;
4
public var stepTimer:Timer;
5
6
//...

7
8
private function getStarted():void
9
{
10
	var gravity:b2Vec2 = new b2Vec2(0, 10);
11
	world = new b2World(gravity, true);
12
	
13
	var wheelBodyDef:b2BodyDef = new b2BodyDef();
14
	wheelBodyDef.type = b2Body.b2_dynamicBody;
15
	wheelBody = world.CreateBody(wheelBodyDef);
16
	var circleShape:b2CircleShape = new b2CircleShape(5);
17
	var wheelFixtureDef:b2FixtureDef = new b2FixtureDef();
18
	wheelFixtureDef.shape = circleShape;
19
	var wheelFixture:b2Fixture = wheelBody.CreateFixture(wheelFixtureDef);
20
	
21
	stepTimer = new Timer(0.025 * 1000);
22
	stepTimer.addEventListener(TimerEvent.TIMER, onTick);
23
	trace(wheelBody.GetPosition().x, wheelBody.GetPosition().y);
24
	stepTimer.start();
25
}

Note that lines 14 and 20, above, have changed, now that the wheel body and timer are defined elsewhere.

Try it now:

1
2
0 0
3
0 0.00625
4
0 0.018750000000000003
5
0 0.037500000000000006
6
0 0.0625
7
0 0.09375
8
0 0.13125
9
0 0.17500000000000002
10
0 0.22500000000000003
11
0 0.28125000000000006
12
0 0.34375000000000006
13
0 0.4125000000000001
14
0 0.4875000000000001
15
0 0.5687500000000001

Hooray, it's falling forever! Okay, that's enough analysing the numbers; let's make something visual.


Step 7: Draw!

We've got all these coordinates, so why not join the dots?

Replace the traces with the code to draw a line from the wheel's old position to its new one:

1
2
private function onTick(a_event:TimerEvent):void
3
{
4
	graphics.moveTo(wheelBody.GetPosition().x, wheelBody.GetPosition().y);
5
	world.Step(0.025, 10, 10);
6
	graphics.lineTo(wheelBody.GetPosition().x, wheelBody.GetPosition().y);
7
}

In order to see the line, we'll need to set its lineStyle:

1
2
private function getStarted():void
3
{
4
5
	//...

6
	
7
	stepTimer = new Timer(0.025 * 1000);
8
	stepTimer.addEventListener(TimerEvent.TIMER, onTick);
9
	graphics.lineStyle(3, 0xff0000);
10
	stepTimer.start();
11
}

Now run the SWF. You'll see a red line accelerating down the left edge. I've added some trickery to my SWF that means it won't do anything until you click it, so you can check it out below:

Great! So, the wheel is free-falling, and getting faster due to gravity, as it should be. We should leave its vertical speed alone so that gravity can do its work, but we can manually alter its initial horizontal speed to make the line's shape a little more interesting:

1
2
private function getStarted():void
3
{
4
5
	//...

6
	
7
	var startingVelocity:b2Vec2 = new b2Vec2(50, 0);
8
	wheelBody.SetLinearVelocity(startingVelocity);
9
	
10
	stepTimer = new Timer(0.025 * 1000);
11
	stepTimer.addEventListener(TimerEvent.TIMER, onTick);
12
	graphics.lineStyle(3, 0xff0000);
13
	stepTimer.start();
14
}

Remember that a b2Vec2 looks like an arrow, so, in this case, the starting velocity is going to look like an arrow pointing directly to the right, as if we had just shot it out of a cannon from the top of a cliff. Our world has no air resistance (because there's no air!) so there's absolutely nothing to slow it down -- though, thanks to gravity, it is speeding up vertically.

Sounds confusing, but it should be clear once you run the SWF:

We've just inadvertently drawn a parabola. So... that's neat, I guess?


Step 9: The Illusion of Movement

Okay, okay, maybe you're not as thrilled to see a curved red line as I am. If we're going to simulate a world, we should make the objects look like, well, objects, right? So instead of seeing a line that traces the wheel's position through space, we should make it look as if the wheel is actually moving through space.

We can do this by repeatedly drawing and erasing a circle, centered on the wheel's location:

1
2
private function onTick(a_event:TimerEvent):void
3
{
4
	graphics.clear();
5
	graphics.lineStyle(3, 0xff0000);
6
	world.Step(0.025, 10, 10);
7
	graphics.drawCircle(wheelBody.GetPosition().x, wheelBody.GetPosition().y, 5);
8
}

We have to specify the line style in onTick() now, because graphics.clear() resets it, as well as erasing all the graphics from the screen. Note that I've set the radius of the circle to 5, which is the same as the radius of the circleShape we created earlier.

Try this SWF:

I think it's pretty obvious what the next step should be...


Step 10: Grounded

This infinite world of nothingness doesn't lend itself to many exciting situations. Sure, we could add new wheels, but without any ground or walls, they'd never do anything interesting.

We'll create some solid objects that the wheel can collide with, starting with a big flat piece of ground. For this, we'll use a rectangle.

Remember the objects we need to create a body?

  • A body definition, which is like a template for creating...
  • A body, which has a mass and a position, but doesn't have...
  • A shape, which could be as simple as a circle, that must be connected to a body using...
  • A fixture, which is created using...
  • A fixture definition which is another template, like the body definition.

You know how to do this for a circular body; now we need to make a rectangular one:

1
2
private function getStarted():void
3
{
4
	var gravity:b2Vec2 = new b2Vec2(0, 10);
5
	world = new b2World(gravity, true);
6
	
7
	var wheelBodyDef:b2BodyDef = new b2BodyDef();
8
	wheelBodyDef.type = b2Body.b2_dynamicBody;
9
	wheelBody = world.CreateBody(wheelBodyDef);
10
	var circleShape:b2CircleShape = new b2CircleShape(5);
11
	var wheelFixtureDef:b2FixtureDef = new b2FixtureDef();
12
	wheelFixtureDef.shape = circleShape;
13
	var wheelFixture:b2Fixture = wheelBody.CreateFixture(wheelFixtureDef);
14
	
15
	var groundBodyDef:b2BodyDef = new b2BodyDef();
16
	var groundBody:b2Body = world.CreateBody(groundBodyDef);
17
	var groundShape:b2PolygonShape = new b2PolygonShape();
18
	groundShape.SetAsBox(stage.stageWidth, 1);
19
	var groundFixtureDef:b2FixtureDef = new b2FixtureDef();
20
	groundFixtureDef.shape = groundShape;
21
	var groundFixture:b2Fixture = groundBody.CreateFixture(groundFixtureDef);
22
	
23
	var startingVelocity:b2Vec2 = new b2Vec2(50, 0);
24
	wheelBody.SetLinearVelocity(startingVelocity);
25
	
26
	stepTimer = new Timer(0.025 * 1000);
27
	stepTimer.addEventListener(TimerEvent.TIMER, onTick);
28
	graphics.lineStyle(3, 0xff0000);
29
	stepTimer.start();
30
}

It's mostly the same, except that, where in creating a circular body we passed the desired radius to the b2CircleShape() constructor, here we must pass the desired width and height of the rectangle to the b2PolygonShape.SetAsBox() function. (Actually, we pass the desired half-width and half-height, so the box will be twice as wide as the stage and two pixels tall, but that's fine.) Remember that all bodies are static by default, so we don't have to worry about the ground falling away. You'll need to import Box2D.Collision.Shapes.b2PolygonShape for this to work.

By default, any new shape will be created at (0, 0), so we need to specify that the ground should be created at the bottom of the stage. We could manually alter the position of the ground body once it's been created, just as we manually altered the velocity of the wheel body, but it's neater if we set the position as part of the ground's body definition:

1
2
private function getStarted():void
3
{
4
	var gravity:b2Vec2 = new b2Vec2(0, 10);
5
	world = new b2World(gravity, true);
6
	
7
	var wheelBodyDef:b2BodyDef = new b2BodyDef();
8
	wheelBodyDef.type = b2Body.b2_dynamicBody;
9
	wheelBody = world.CreateBody(wheelBodyDef);
10
	var circleShape:b2CircleShape = new b2CircleShape(5);
11
	var wheelFixtureDef:b2FixtureDef = new b2FixtureDef();
12
	wheelFixtureDef.shape = circleShape;
13
	var wheelFixture:b2Fixture = wheelBody.CreateFixture(wheelFixtureDef);
14
	
15
	var groundBodyDef:b2BodyDef = new b2BodyDef();
16
	groundBodyDef.position.Set(0, stage.stageHeight);
17
	var groundBody:b2Body = world.CreateBody(groundBodyDef);
18
	var groundShape:b2PolygonShape = new b2PolygonShape();
19
	groundShape.SetAsBox(stage.stageWidth, 1);
20
	var groundFixtureDef:b2FixtureDef = new b2FixtureDef();
21
	groundFixtureDef.shape = groundShape;
22
	var groundFixture:b2Fixture = groundBody.CreateFixture(groundFixtureDef);
23
	
24
	var startingVelocity:b2Vec2 = new b2Vec2(50, 0);
25
	wheelBody.SetLinearVelocity(startingVelocity);
26
	
27
	stepTimer = new Timer(0.025 * 1000);
28
	stepTimer.addEventListener(TimerEvent.TIMER, onTick);
29
	graphics.lineStyle(3, 0xff0000);
30
	stepTimer.start();
31
}

Make sure you set this before passing the body definition to world.CreateBody(), or the changes will be ignored.

Now test the SWF:

We can't see the ground because we haven't drawn it, but Box2D still simulates it, so we see its effect: the wheel collides with it and rolls to the side.


Step 11: Set Some Boundaries

We're going to add more wheels in the next step, but first, let's make this a completely enclosed space, with a ground, a ceiling, and two walls.

I'd like you to have a go at this yourself; create three more rectangular bodies of the right sizes and in the right positions. It'll be easiest to start with the one on the right, since the wheel is going to collide with it. To test the others, fiddle about with the initial velocity.

You'll need to change the wheel's initial position, or it'll overlap the left wall and the ceiling when they're created. You can do this in the same way that you set the position of the rectangular objects, through the position.Set() method of the body definition.

Good luck! If you get stuck, check out my code below:

1
2
private function getStarted():void
3
{
4
	var gravity:b2Vec2 = new b2Vec2(0, 10);
5
	world = new b2World(gravity, true);
6
	
7
	var wheelBodyDef:b2BodyDef = new b2BodyDef();
8
	wheelBodyDef.type = b2Body.b2_dynamicBody;
9
	wheelBodyDef.position.Set(10, 10);
10
	wheelBody = world.CreateBody(wheelBodyDef);
11
	var circleShape:b2CircleShape = new b2CircleShape(5);
12
	var wheelFixtureDef:b2FixtureDef = new b2FixtureDef();
13
	wheelFixtureDef.shape = circleShape;
14
	var wheelFixture:b2Fixture = wheelBody.CreateFixture(wheelFixtureDef);
15
	
16
	var groundBodyDef:b2BodyDef = new b2BodyDef();
17
	groundBodyDef.position.Set(0, stage.stageHeight);
18
	var groundBody:b2Body = world.CreateBody(groundBodyDef);
19
	var groundShape:b2PolygonShape = new b2PolygonShape();
20
	groundShape.SetAsBox(stage.stageWidth, 1);
21
	var groundFixtureDef:b2FixtureDef = new b2FixtureDef();
22
	groundFixtureDef.shape = groundShape;
23
	var groundFixture:b2Fixture = groundBody.CreateFixture(groundFixtureDef);
24
	
25
	var rightWallBodyDef:b2BodyDef = new b2BodyDef();
26
	rightWallBodyDef.position.Set(stage.stageWidth, 0);
27
	var rightWallBody:b2Body = world.CreateBody(rightWallBodyDef);
28
	var rightWallShape:b2PolygonShape = new b2PolygonShape();
29
	rightWallShape.SetAsBox(1, stage.stageHeight);
30
	var rightWallFixtureDef:b2FixtureDef = new b2FixtureDef();
31
	rightWallFixtureDef.shape = rightWallShape;
32
	var rightWallFixture:b2Fixture = rightWallBody.CreateFixture(rightWallFixtureDef);
33
	
34
	var leftWallBodyDef:b2BodyDef = new b2BodyDef();
35
	leftWallBodyDef.position.Set(0, 0);
36
	var leftWallBody:b2Body = world.CreateBody(leftWallBodyDef);
37
	var leftWallShape:b2PolygonShape = new b2PolygonShape();
38
	leftWallShape.SetAsBox(1, stage.stageHeight);
39
	var leftWallFixtureDef:b2FixtureDef = new b2FixtureDef();
40
	leftWallFixtureDef.shape = leftWallShape;
41
	var leftWallFixture:b2Fixture = leftWallBody.CreateFixture(leftWallFixtureDef);
42
	
43
	var ceilingBodyDef:b2BodyDef = new b2BodyDef();
44
	ceilingBodyDef.position.Set(0, 0);
45
	var ceilingBody:b2Body = world.CreateBody(ceilingBodyDef);
46
	var ceilingShape:b2PolygonShape = new b2PolygonShape();
47
	ceilingShape.SetAsBox(stage.stageWidth, 1);
48
	var ceilingFixtureDef:b2FixtureDef = new b2FixtureDef();
49
	ceilingFixtureDef.shape = ceilingShape;
50
	var ceilingFixture:b2Fixture = ceilingBody.CreateFixture(ceilingFixtureDef);
51
	
52
	var startingVelocity:b2Vec2 = new b2Vec2(50, 0);
53
	wheelBody.SetLinearVelocity(startingVelocity);
54
	
55
	stepTimer = new Timer(0.025 * 1000);
56
	stepTimer.addEventListener(TimerEvent.TIMER, onTick);
57
	graphics.lineStyle(3, 0xff0000);
58
	stepTimer.start();
59
}

And the result:

Nice work.


Step 12: Create an Array

Now we're ready to add more bodies, slam them together, and see what happens.

We could create them all invididually, like I did with the rectangles, but it'd be neater to use an array to hold them all, and a single function to create them.

So, first, let's create that array, with a single element: the existing wheel.

1
2
public var world:b2World;
3
//public var wheelBody:b2Body; <-- delete this line

4
public var wheelArray:Array;
5
public var stepTimer:Timer;
6
7
//...

8
9
private function getStarted():void
10
{
11
	var gravity:b2Vec2 = new b2Vec2(0, 10);
12
	world = new b2World(gravity, true);
13
	
14
	wheelArray = new Array();
15
	
16
	var wheelBodyDef:b2BodyDef = new b2BodyDef();
17
	wheelBodyDef.type = b2Body.b2_dynamicBody;
18
	wheelBodyDef.position.Set(10, 10);
19
	var wheelBody:b2Body = world.CreateBody(wheelBodyDef);
20
	var circleShape:b2CircleShape = new b2CircleShape(5);
21
	var wheelFixtureDef:b2FixtureDef = new b2FixtureDef();
22
	wheelFixtureDef.shape = circleShape;
23
	var wheelFixture:b2Fixture = wheelBody.CreateFixture(wheelFixtureDef);
24
	
25
	wheelArray.push(wheelBody);
26
	
27
	//...

28
	
29
	var startingVelocity:b2Vec2 = new b2Vec2(50, 0);
30
	wheelBody.SetLinearVelocity(startingVelocity);
31
	
32
	stepTimer = new Timer(0.025 * 1000);
33
	stepTimer.addEventListener(TimerEvent.TIMER, onTick);
34
	graphics.lineStyle(3, 0xff0000);
35
	stepTimer.start();
36
}
37
38
private function onTick(a_event:TimerEvent):void
39
{
40
	graphics.clear();
41
	graphics.lineStyle(3, 0xff0000);
42
	world.Step(0.025, 10, 10);
43
	
44
	for each (var wheelBody:b2Body in wheelArray)
45
	{
46
		graphics.drawCircle(wheelBody.GetPosition().x, wheelBody.GetPosition().y, 5);
47
	}
48
}

If this works, your SWF will act exactly the same as it did before.


Step 13: Add One More Wheel

To test this out properly, we can add an extra wheel -- just one for now! Copy and paste the code for creating the wheel and change parts of it so the wheels aren't exactly the same:

1
2
private function getStarted():void
3
{
4
	var gravity:b2Vec2 = new b2Vec2(0, 10);
5
	world = new b2World(gravity, true);
6
	
7
	wheelArray = new Array();
8
	
9
	var wheelBodyDef:b2BodyDef = new b2BodyDef();
10
	wheelBodyDef.type = b2Body.b2_dynamicBody;
11
	wheelBodyDef.position.Set(10, 10);
12
	var wheelBody:b2Body = world.CreateBody(wheelBodyDef);
13
	var circleShape:b2CircleShape = new b2CircleShape(5);
14
	var wheelFixtureDef:b2FixtureDef = new b2FixtureDef();
15
	wheelFixtureDef.shape = circleShape;
16
	var wheelFixture:b2Fixture = wheelBody.CreateFixture(wheelFixtureDef);
17
	
18
	wheelArray.push(wheelBody);
19
	
20
	var wheelBodyDef:b2BodyDef = new b2BodyDef();
21
	wheelBodyDef.type = b2Body.b2_dynamicBody;
22
	wheelBodyDef.position.Set(100, 200);
23
	var wheelBody:b2Body = world.CreateBody(wheelBodyDef);
24
	var circleShape:b2CircleShape = new b2CircleShape(5);
25
	var wheelFixtureDef:b2FixtureDef = new b2FixtureDef();
26
	wheelFixtureDef.shape = circleShape;
27
	var wheelFixture:b2Fixture = wheelBody.CreateFixture(wheelFixtureDef);
28
	
29
	wheelArray.push(wheelBody);
30
	
31
	//... create boundaries here

32
	
33
	var startingVelocity:b2Vec2 = new b2Vec2(50, 0);
34
	wheelBody.SetLinearVelocity(startingVelocity);
35
	
36
	stepTimer = new Timer(0.025 * 1000);
37
	stepTimer.addEventListener(TimerEvent.TIMER, onTick);
38
	graphics.lineStyle(3, 0xff0000);
39
	stepTimer.start();
40
}

You'll get a bunch of warnings about duplicate variable definitions, but it should still compile, depending on your settings:

The first wheel drops straight down, without an initial sideways velocity. This makes perfect sense when you look at the code; we're calling wheelBody.SetLinearVelocity() in the wrong place. Move it up:

1
2
private function getStarted():void
3
{
4
	var gravity:b2Vec2 = new b2Vec2(0, 10);
5
	world = new b2World(gravity, true);
6
	
7
	wheelArray = new Array();
8
	
9
	var wheelBodyDef:b2BodyDef = new b2BodyDef();
10
	wheelBodyDef.type = b2Body.b2_dynamicBody;
11
	wheelBodyDef.position.Set(10, 10);
12
	var wheelBody:b2Body = world.CreateBody(wheelBodyDef);
13
	var circleShape:b2CircleShape = new b2CircleShape(5);
14
	var wheelFixtureDef:b2FixtureDef = new b2FixtureDef();
15
	wheelFixtureDef.shape = circleShape;
16
	var wheelFixture:b2Fixture = wheelBody.CreateFixture(wheelFixtureDef);
17
	
18
	var startingVelocity:b2Vec2 = new b2Vec2(50, 0);
19
	wheelBody.SetLinearVelocity(startingVelocity);
20
	
21
	wheelArray.push(wheelBody);
22
	
23
	var wheelBodyDef:b2BodyDef = new b2BodyDef();
24
	wheelBodyDef.type = b2Body.b2_dynamicBody;
25
	wheelBodyDef.position.Set(100, 200);
26
	var wheelBody:b2Body = world.CreateBody(wheelBodyDef);
27
	var circleShape:b2CircleShape = new b2CircleShape(5);
28
	var wheelFixtureDef:b2FixtureDef = new b2FixtureDef();
29
	wheelFixtureDef.shape = circleShape;
30
	var wheelFixture:b2Fixture = wheelBody.CreateFixture(wheelFixtureDef);
31
	
32
	var startingVelocity:b2Vec2 = new b2Vec2(-100, 0);
33
	wheelBody.SetLinearVelocity(startingVelocity);
34
	
35
	wheelArray.push(wheelBody);
36
	
37
	//... create boundaries here

38
	
39
	stepTimer = new Timer(0.025 * 1000);
40
	stepTimer.addEventListener(TimerEvent.TIMER, onTick);
41
	graphics.lineStyle(3, 0xff0000);
42
	stepTimer.start();
43
}

Okay! That's working well. We can wrap all that wheel creation code up in a function, now.


Step 14: Wheel Generator

To create this wheel generation function, you can basically copy and paste all the code we've been using. Here's mine:

1
2
private function createWheel(radius:Number, startX:Number, startY:Number, velocityX:Number, velocityY:Number):void
3
{
4
	var wheelBodyDef:b2BodyDef = new b2BodyDef();
5
	wheelBodyDef.type = b2Body.b2_dynamicBody;
6
	wheelBodyDef.position.Set(startX, startY);
7
	var wheelBody:b2Body = world.CreateBody(wheelBodyDef);
8
	var circleShape:b2CircleShape = new b2CircleShape(radius);
9
	var wheelFixtureDef:b2FixtureDef = new b2FixtureDef();
10
	wheelFixtureDef.shape = circleShape;
11
	var wheelFixture:b2Fixture = wheelBody.CreateFixture(wheelFixtureDef);
12
	
13
	var startingVelocity:b2Vec2 = new b2Vec2(velocityX, velocityY);
14
	wheelBody.SetLinearVelocity(startingVelocity);
15
	
16
	wheelArray.push(wheelBody);
17
}

I've added some parameters so that we can specify the customisable properties of the wheels. While we're at it, I suggest we move all of the boundary creation code to a separate function, just to keep things tidy:

1
2
private function createBoundaries():void
3
{
4
	//insert your boundary code here

5
}

Now we can rewrite the entire getStarted() function like so:

1
2
private function getStarted():void
3
{
4
	var gravity:b2Vec2 = new b2Vec2(0, 10);
5
	world = new b2World(gravity, true);
6
	wheelArray = new Array();
7
	
8
	createWheel(5, 10, 10, 50, 0);
9
	createWheel(5, 100, 200, -25, 0);
10
	
11
	createBoundaries();
12
	
13
	stepTimer = new Timer(0.025 * 1000);
14
	stepTimer.addEventListener(TimerEvent.TIMER, onTick);
15
	graphics.lineStyle(3, 0xff0000);
16
	stepTimer.start();
17
}

Try it out! Again, the SWF should act the same as it did before.


Step 15: Automatic Wheels

Now that we've simplified the wheel generation, we can make lots of them without much difficulty or mess:

1
2
private function getStarted():void
3
{
4
	var gravity:b2Vec2 = new b2Vec2(0, 10);
5
	world = new b2World(gravity, true);
6
	wheelArray = new Array();
7
	
8
	for (var i:int = 0; i < 20; i++)
9
	{
10
		createWheel(
11
			Math.random() * 10,
12
			Math.random() * (stage.stageWidth - 20) + 10,
13
			Math.random() * (stage.stageHeight - 20) + 10,
14
			(Math.random() * 100) - 50,
15
			0
16
		);
17
	}
18
	
19
	createBoundaries();
20
	
21
	stepTimer = new Timer(0.025 * 1000);
22
	stepTimer.addEventListener(TimerEvent.TIMER, onTick);
23
	graphics.lineStyle(3, 0xff0000);
24
	stepTimer.start();
25
}

This will create twenty wheels, each with a radius of between 0 and 10, a position of anywhere between (10, 10) and (stageWidth-10, stageHeight-10), and a horizontal speed of anywhere between -50 and +50. Try it out!

It almost works, but something's wrong. Let's figure out what's going on.


Step 16: Spoiler -- It's the Radius

Check out this image from when I ran the SWF:

Some of the wheels are sunk into the ground or wall, and some are overlapping each other. It's really weird. And on a related note, didn't we set the radii of the wheels to be anywhere between 0 and 10? Why are they all the same?

As you've probably figured out, they're the same because we hard coded the radius of the circle to draw in the onTick() event handler function. Oops.

Unfortunately we can't just use wheelBody.radius to find the radius of the wheel; remember that the body doesn't have a shape, but rather is connected to a shape through a fixture. To find the radius, then, we have to do something like this:

1
2
var wheelFixture:b2Fixture = wheelBody.GetFixtureList();
3
var wheelShape:b2CircleShape = wheelFixture.GetShape() as b2CircleShape;
4
var radius:Number = wheelShape.GetRadius();

Fortunately we can simplify this to (wheelBody.GetFixtureList().GetShape() as b2CircleShape).GetRadius(); let's use this in onTick():

1
2
private function onTick(a_event:TimerEvent):void
3
{
4
	graphics.clear();
5
	graphics.lineStyle(3, 0xff0000);
6
	world.Step(0.025, 10, 10);
7
8
	for each (var wheelBody:b2Body in wheelArray)
9
	{
10
		graphics.drawCircle(
11
			wheelBody.GetPosition().x, 
12
			wheelBody.GetPosition().y, 
13
			(wheelBody.GetFixtureList().GetShape() as b2CircleShape).GetRadius()
14
		);
15
		
16
	}
17
}

How's that?

Ah, much better!


Step 17: Have a Little Fun

The simulation is a little dull at the moment; the wheels just roll a little bit and then stop. Boring. Let's liven things up a bit by changing them from metal wheels to air-filled rubber tyres.

To do this, we can use a property called the coefficient of restitution. This is physics-talk for "bounciness"; the coefficient of restitution of an object shows how much it will bounce back after colliding with another object. Typically, this takes a value between 0 and 1, where 0 means it stops dead as soon as it touches another object, and 1 means it bounces back without losing any energy.

By default, all Box2D bodies have a coefficient of restitution of 0; let's liven things up by setting it a bit higher:

1
2
private function createWheel(radius:Number, startX:Number, startY:Number, velocityX:Number, velocityY:Number):void
3
{
4
	var wheelBodyDef:b2BodyDef = new b2BodyDef();
5
	wheelBodyDef.type = b2Body.b2_dynamicBody;
6
	wheelBodyDef.position.Set(startX, startY);
7
	var wheelBody:b2Body = world.CreateBody(wheelBodyDef);
8
	var circleShape:b2CircleShape = new b2CircleShape(radius);
9
	var wheelFixtureDef:b2FixtureDef = new b2FixtureDef();
10
	wheelFixtureDef.shape = circleShape;
11
	wheelFixtureDef.restitution = (Math.random() * 0.5) + 0.5;
12
	var wheelFixture:b2Fixture = wheelBody.CreateFixture(wheelFixtureDef);
13
	
14
	var startingVelocity:b2Vec2 = new b2Vec2(velocityX, velocityY);
15
	wheelBody.SetLinearVelocity(startingVelocity);
16
	
17
	wheelArray.push(wheelBody);
18
}

This will set the coefficient of restitution of each wheel to a random value between 0.5 and 1. Note that this is a property of the fixture definition, rather than the shape or the body definition.

Let's see what happens:

That's more like it! What else can we set?


Step 18: Other Properties

We can also set the friction (how rough or smooth the outer surface is; a polished steel wheel will have less friction than a rough stone one) and the density (how heavy the body would be compared to another of the same size and shape; stone is denser than wood).

The friction coefficient should be between 0 and 1, where 0 means extremely smooth and 1 means extremely rough, and is 0.2 by default. The density can be any value you like, and is 1 by default. (Well, for static bodies, it's 0, but it doesn't really matter to them as they don't move anyway.)

Let's mess around with these values and see what happens:

1
2
private function createWheel(radius:Number, startX:Number, startY:Number, velocityX:Number, velocityY:Number):void
3
{
4
	var wheelBodyDef:b2BodyDef = new b2BodyDef();
5
	wheelBodyDef.type = b2Body.b2_dynamicBody;
6
	wheelBodyDef.position.Set(startX, startY);
7
	var wheelBody:b2Body = world.CreateBody(wheelBodyDef);
8
	var circleShape:b2CircleShape = new b2CircleShape(radius);
9
	var wheelFixtureDef:b2FixtureDef = new b2FixtureDef();
10
	wheelFixtureDef.shape = circleShape;
11
	wheelFixtureDef.restitution = (Math.random() * 0.5) + 0.5;
12
	wheelFixtureDef.friction = (Math.random() * 1.0);
13
	wheelFixtureDef.density = Math.random() * 20;
14
	var wheelFixture:b2Fixture = wheelBody.CreateFixture(wheelFixtureDef);
15
	
16
	var startingVelocity:b2Vec2 = new b2Vec2(velocityX, velocityY);
17
	wheelBody.SetLinearVelocity(startingVelocity);
18
	
19
	wheelArray.push(wheelBody);
20
}

The result:

All good. Feel free to add parameters for restitution, friction, and density to the createWheel() function if you want a bit more control.

There's something that's bugging me, though...


Step 19: Heavy, Man

...Why does everything feel so floaty?

Seriously, it's like the whole world is moving through treacle. But there's no air resistance, let alone molasses resistance; gravity is at a sensible level; and the time step is matched to the timer's tick duration -- what's the issue?

If you're a scientist, you've probably noticed that I haven't mentioned any units in the whole tutorial. The first wheel's radius was just "5" -- not "5 inches" or whatever. We've just been working in pixels. But Box2D is a physics engine, and so it uses actual physical units. That wheel had a radius of five meters, not five pixels; that's roughly sixteen feet, not far off the height of an average house. Most wheels aren't that height, although there are exceptions, as this Flickr photo from Monochrome shows:

Even then, the tires in that photo have a radius of about 2.5 meters; we'd normally expect a wheel's radius to be somewhere between a few centimetres and half a meter. This means that every Box2D object we've created is much bigger than it appears on the screen, and -- as anyone who's watched Honey I Shrunk The Kids knows -- bigger objects move in slow motion.

So, we can get a much less floaty simulation by changing the radius of the wheels that we create:

1
2
for (var i:int = 0; i < 20; i++)
3
{
4
	createWheel(
5
		Math.random() * 0.5,
6
		Math.random() * (stage.stageWidth - 20) + 10,
7
		Math.random() * (stage.stageHeight - 20) + 10,
8
		(Math.random() * 100) - 50,
9
		0
10
	);
11
}

The resulting SWF feels a lot more realistic, but at the same time, the wheels are all drawn so tiny that it feels like we're watching from half a mile away:

There's a common trick that Box2D developers use here...


Step 20: Set the Scale Factor

To recap: Box2D uses meters, but Flash uses pixels. Therefore, a wheel of 0.5 meters in radius is drawn as a tiny circle, just over a pixel wide.

When you read it like that, perhaps the solution seems obvious: we need to scale up the conversion between meters and pixels, so that one meter is drawn as, let's say, 20 pixels.

Modify the graphics.drawCircle() call in onTick() to reflect this new scale factor:

1
2
private function onTick(a_event:TimerEvent):void
3
{
4
	graphics.clear();
5
	graphics.lineStyle(3, 0xff0000);
6
	world.Step(0.025, 10, 10);
7
8
	for each (var wheelBody:b2Body in wheelArray)
9
	{
10
		graphics.drawCircle(
11
			wheelBody.GetPosition().x,
12
			wheelBody.GetPosition().y,
13
			(wheelBody.GetFixtureList().GetShape() as b2CircleShape).GetRadius() * 20
14
		);
15
		
16
	}
17
}

Does that work?

Um, no. We're back to floatiness, plus the wheels aren't colliding with each other any more.

Ah, but, this is misleading. The graphical representations of the wheels appear to be overlapping, but actually, they're not. See, we can't just use this scale factor for the radii of the wheels and leave it at that; we have to use it for all lengths and distances -- and that includes the x- and y-positions of the wheels. So, try this:

1
2
private function onTick(a_event:TimerEvent):void
3
{
4
	graphics.clear();
5
	graphics.lineStyle(3, 0xff0000);
6
	world.Step(0.025, 10, 10);
7
	
8
	for each (var wheelBody:b2Body in wheelArray)
9
	{
10
		graphics.drawCircle(
11
			wheelBody.GetPosition().x * 20,
12
			wheelBody.GetPosition().y * 20,
13
			(wheelBody.GetFixtureList().GetShape() as b2CircleShape).GetRadius() * 20
14
		);
15
		
16
	}
17
}

Actually, hold on -- let's use a public variable instead of hard coding the number 20:

1
2
public var scaleFactor:Number = 20;		//pixels per meter

3
4
//...

5
6
private function onTick(a_event:TimerEvent):void
7
{
8
	graphics.clear();
9
	graphics.lineStyle(3, 0xff0000);
10
	world.Step(0.025, 10, 10);
11
	
12
	for each (var wheelBody:b2Body in wheelArray)
13
	{
14
		graphics.drawCircle(
15
			wheelBody.GetPosition().x * scaleFactor,
16
			wheelBody.GetPosition().y * scaleFactor,
17
			(wheelBody.GetFixtureList().GetShape() as b2CircleShape).GetRadius() * scaleFactor
18
		);
19
		
20
	}
21
}

Try the SWF now, and... hmm. Just a blank white canvas. Let's see what's going on under the hood:

1
2
for each (var wheelBody:b2Body in wheelArray)
3
{
4
	trace(wheelBody.GetPosition().x * 20, wheelBody.GetPosition().y * 20);
5
	graphics.drawCircle(
6
		wheelBody.GetPosition().x * scaleFactor,
7
		wheelBody.GetPosition().y * scaleFactor,
8
		(wheelBody.GetFixtureList().GetShape() as b2CircleShape).GetRadius() * scaleFactor
9
	);
10
	
11
}

Result:

1
2
2113.750333013013 5770.15641567111
3
9375.355269713327 3047.2614786848426
4
1777.8544335393235 7079.051908224821
5
5187.372552766465 3558.7625446990132
6
918.4206030098721 1295.5237261280417
7
6346.797422436066 4702.557933263481
8
5711.968449363485 6922.446605682373
9
3969.2852629581466 493.93064894527197
10
288.0119406618178 2824.054687216878
11
7364.996945206076 7429.401991263032
12
6689.968886575662 6163.817259043455
13
3496.4873051736504 3063.40289388597
14
7230.636887997389 1294.561620734632
15
5069.327887007967 7544.009161673486
16
7484.348242566921 3492.7868475466967
17
3882.391231972724 6486.211738668382
18
1641.0604398231953 2738.4121247828007
19
9631.735268328339 3224.4683633819222

Whoa! Those numbers are wayyy too big. But that makes sense -- they're 20 times bigger than they used to be.

Think about when we create the wheels -- and specifically, when we set their initial positions:

1
2
createWheel(
3
	Math.random() * 0.5,
4
	Math.random() * (stage.stageWidth - 20) + 10,
5
	Math.random() * (stage.stageHeight - 20) + 10,
6
	(Math.random() * 100) - 50,
7
	0
8
);

My stage is 500x400px. When I wasn't using a scale factor, a new wheel's x-position could be anywhere from 10px to 490px from the left of the stage. This was the same as being anywhere from 10 meters to 490 meters from the left of the stage, because each meter was represented as a single pixel long. But now, each meter is represented by twenty pixels -- so a new wheel's x-position could be anywhere from 200px to 9800px from the left of the stage! No wonder we're not seeing any of them.

To fix this, we'll use the scale factor in the code that creates a new wheel:

1
2
private function createWheel(radius:Number, startX:Number, startY:Number, velocityX:Number, velocityY:Number):void
3
{
4
	var wheelBodyDef:b2BodyDef = new b2BodyDef();
5
	wheelBodyDef.type = b2Body.b2_dynamicBody;
6
	wheelBodyDef.position.Set(startX / scaleFactor, startY / scaleFactor);
7
	var wheelBody:b2Body = world.CreateBody(wheelBodyDef);
8
	var circleShape:b2CircleShape = new b2CircleShape(radius);
9
	var wheelFixtureDef:b2FixtureDef = new b2FixtureDef();
10
	wheelFixtureDef.shape = circleShape;
11
	wheelFixtureDef.restitution = (Math.random() * 0.5) + 0.5;
12
	wheelFixtureDef.friction = (Math.random() * 1.0);
13
	wheelFixtureDef.density = Math.random() * 20;
14
	var wheelFixture:b2Fixture = wheelBody.CreateFixture(wheelFixtureDef);
15
	
16
	var startingVelocity:b2Vec2 = new b2Vec2(velocityX, velocityY);
17
	wheelBody.SetLinearVelocity(startingVelocity);
18
	
19
	wheelArray.push(wheelBody);
20
}

Does it make sense to you that we're dividing it, rather than multiplying it? Remember, Box2D uses meters, Flash uses pixels, and our scale factor is in pixels/meter.

Try the SWF now:

Much better -- but the right wall and ground appear to have disappeared.

...Have you already guessed what's happening?

It's because, again, the distances are specified in meters, and we haven't applied the scale factor. So rather than the right wall being 500px from the left edge, it's 500 meters, or 10,000px. Again, we need to divide our distances by the scale factor to take this into account.

If you wrote this code yourself, I'm sure you can figure out how to alter it yourself :) Otherwise, here's mine:

1
2
private function createBoundaries():void
3
{
4
	var groundBodyDef:b2BodyDef = new b2BodyDef();
5
	groundBodyDef.position.Set(0, stage.stageHeight / scaleFactor);
6
	var groundBody:b2Body = world.CreateBody(groundBodyDef);
7
	var groundShape:b2PolygonShape = new b2PolygonShape();
8
	groundShape.SetAsBox(stage.stageWidth / scaleFactor, 1 / scaleFactor);
9
	var groundFixtureDef:b2FixtureDef = new b2FixtureDef();
10
	groundFixtureDef.shape = groundShape;
11
	var groundFixture:b2Fixture = groundBody.CreateFixture(groundFixtureDef);
12
	
13
	var rightWallBodyDef:b2BodyDef = new b2BodyDef();
14
	rightWallBodyDef.position.Set(stage.stageWidth / scaleFactor, 0);
15
	var rightWallBody:b2Body = world.CreateBody(rightWallBodyDef);
16
	var rightWallShape:b2PolygonShape = new b2PolygonShape();
17
	rightWallShape.SetAsBox(1 / scaleFactor, stage.stageHeight / scaleFactor);
18
	var rightWallFixtureDef:b2FixtureDef = new b2FixtureDef();
19
	rightWallFixtureDef.shape = rightWallShape;
20
	var rightWallFixture:b2Fixture = rightWallBody.CreateFixture(rightWallFixtureDef);
21
	
22
	var leftWallBodyDef:b2BodyDef = new b2BodyDef();
23
	leftWallBodyDef.position.Set(0, 0);
24
	var leftWallBody:b2Body = world.CreateBody(leftWallBodyDef);
25
	var leftWallShape:b2PolygonShape = new b2PolygonShape();
26
	leftWallShape.SetAsBox(1 / scaleFactor, stage.stageHeight / scaleFactor);
27
	var leftWallFixtureDef:b2FixtureDef = new b2FixtureDef();
28
	leftWallFixtureDef.shape = leftWallShape;
29
	var leftWallFixture:b2Fixture = leftWallBody.CreateFixture(leftWallFixtureDef);
30
	
31
	var ceilingBodyDef:b2BodyDef = new b2BodyDef();
32
	ceilingBodyDef.position.Set(0, 0);
33
	var ceilingBody:b2Body = world.CreateBody(ceilingBodyDef);
34
	var ceilingShape:b2PolygonShape = new b2PolygonShape();
35
	ceilingShape.SetAsBox(stage.stageWidth / scaleFactor, 1 / scaleFactor);
36
	var ceilingFixtureDef:b2FixtureDef = new b2FixtureDef();
37
	ceilingFixtureDef.shape = ceilingShape;
38
	var ceilingFixture:b2Fixture = ceilingBody.CreateFixture(ceilingFixtureDef);
39
}

Try it now:

Excellent! And since the scale factor is soft-coded, you could try increasing it:


Conclusion

Congratulations! If you've followed this far, then you understand the very important basic concepts of Box2D. (If you didn't follow this far, then post a comment explaining where you got stuck, and I'll help you out.) Okay, the final SWF might not look like much, but don't be fooled; you've given yourself an excellent framework for what you'll learn next.

Speaking of what's next... what do you want to learn? I've got plenty of ideas, and I'm happy to continue this series in whatever direction I'd like to explore, but it'd be cool to know what you think. Do you want to make a physics puzzler? A platformer? A side-scrolling racing game? Are there any core concepts you'd like to focus on, like creating joints?

The next tutorial in this series will most likely be about rendering objects using other methods than the built-in drawing methods -- in particular we'll look at using DisplayObjects, either drawn through Flash or imported as Bitmaps. We'll also create some actual boxes, because it's pretty weird to have done an entire Box2D tutorial without any.




You can vote on tutorial ideas through our Google Moderator page at http://bit.ly/Box2DFlashTutorialIdeas, or submit a brand new one, if nobody's thought of it yet. Looking forward to seeing what you suggest!

Advertisement
Did you find this post useful?
Want a weekly email summary?
Subscribe below and we’ll send you a weekly email summary of all new Code tutorials. Never miss out on learning about the next big thing.
Advertisement
Looking for something to help kick start your next project?
Envato Market has a range of items for sale to help get you started.