Box2D tutorial for the absolute beginners – revamped

About a year ago I published a Box2D tutorial for the absolute beginners.

With 2.1 release, a lot of things changed, so it’s time to publish another tutorial for the absolute beginners.

In this tutorial we’ll cover needed libraries to import, world creation, debug draw and the creation of static and dynamic boxes and circles. And obviously the simulation itself

This is the movie we are going to make:

And this is the script used to do it:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
package {
	import flash.display.Sprite;
	import flash.events.Event;
	import Box2D.Dynamics.*;
	import Box2D.Collision.*;
	import Box2D.Collision.Shapes.*;
	import Box2D.Common.Math.*;
	public class absolute extends Sprite {
		public var world:b2World=new b2World(new b2Vec2(0,10.0),true);
		public var world_scale:int=30;
		public function absolute():void {
			debug_draw();
			draw_box(250,300,500,100,false);
			draw_box(250,100,100,100,true);
			draw_circle(100,100,50,false);
			draw_circle(400,100,50,true);
			addEventListener(Event.ENTER_FRAME, update);
		}
		public function draw_circle(px,py,r,d):void {
			var my_body:b2BodyDef= new b2BodyDef();
			my_body.position.Set(px/world_scale, py/world_scale);
			if (d) {
				my_body.type=b2Body.b2_dynamicBody;
			}
			var my_circle:b2CircleShape=new b2CircleShape(r/world_scale);
			var my_fixture:b2FixtureDef = new b2FixtureDef();
			my_fixture.shape=my_circle;
			var world_body:b2Body=world.CreateBody(my_body);
			world_body.CreateFixture(my_fixture);
		}
		public function draw_box(px,py,w,h,d):void {
			var my_body:b2BodyDef= new b2BodyDef();
			my_body.position.Set(px/world_scale, py/world_scale);
			if (d) {
				my_body.type=b2Body.b2_dynamicBody;
			}
			var my_box:b2PolygonShape = new b2PolygonShape();
			my_box.SetAsBox(w/2/world_scale, h/2/world_scale);
			var my_fixture:b2FixtureDef = new b2FixtureDef();
			my_fixture.shape=my_box;
			var world_body:b2Body=world.CreateBody(my_body);
			world_body.CreateFixture(my_fixture);
		}
		public function debug_draw():void {
			var debug_draw:b2DebugDraw = new b2DebugDraw();
			var debug_sprite:Sprite = new Sprite();
			addChild(debug_sprite);
			debug_draw.SetSprite(debug_sprite);
			debug_draw.SetDrawScale(world_scale);
			debug_draw.SetFlags(b2DebugDraw.e_shapeBit);
			world.SetDebugDraw(debug_draw);
		}
		public function update(e : Event):void {
			world.Step(1/30,10,10);
			world.ClearForces();
			world.DrawDebugData();
		}
	}
}

Libraries

Libraries are imported at lines 4-7. Box2D folder and your .fla and .as files must be in the same folder

World creation

The only line needed to create an empty world is line 9. The world class is b2World and you must pass two parameters:

* the first one is a vector representing the world gravity.

* the second one is a boolean that allows you to improve performance by not simulating inactive bodies. In Box2D terminology, an inactive body is called “sleeping body”.

Now the world is ready, but you must face the problem of representing meters with pixels. Box2D works with meters, and there is a rule saying 1 meter = 30pixels. That’s why at line 10 I am declaring world_scale at 30. You can find more information about pixels and meters at this post.

Debug draw

As you should know, Box2D does not render the scene, it’s up to you attaching real objects to Box2D bodies. Anyway, there is a debug environment you can see at lines 44-52. This is the simplest debug draw you can make: basically you create a sprite and assign it to a b2DebugDraw class. More theory about debug draw theory at this post.

There are more options to configure the debug draw, but at the moment we are keeping things as simpler as we can. Notice at line 49 how I am setting the debug scale at the same value of the world scale.

Creation of a box

The most basic box is defined by an origin (the centre of the box), a width and an height. We are doing it at lines 31-43.

Let’s see the anatomy of a simple Box2D box.

A box is a body that must be static or dynamic. Only dynamic boxes are affected by gravity, collisions and physics forces. Static ones remain immovable.

Once we create a body (line 32) place it into the world (line 33) and set it as dynamic or not (lines 34-36), we just created a generic body.

It’s time to create a polygon shape (line 37) and define it as a box (line 38). Notice when I define the shape as a box, both width and height are divided by the world scale and by 2. The second division is necessary because the SetAsBox function wants the half width and the half height.

Now we have a body and a polygon. It’s time to create a fixture. The fixture will hold various attributes such as density and restitution, but at the moment to keep things easy I just want to create a fixture (line 39) and assigning it the polygon shape previously created (line 40)

Then it’s time to place the generic body in the world (line 41) and to assign it the fixture previously created with the attached shape (line 42).

And finally the box is created.

Creation of a circle

The creation of a circle is very similar to the box creation, the only difference is the shape this time is a circle shape (line 25) the radius as parameter.

The simulation

We simulate the world in three steps: first we update the world (line 54) passing the amount of time to simulate (normally 1/30), the velocity constraint solver and the position constraint solver.

Constraint solvers determine how many times the engine sweeps over all the contacts and joints in the world to find the final position and velocity of each body. More iterations always yields a better simulation.

Finally we need to clear forces (line 55) to give more stability and it’s time to draw the debug data (line 56) if you are using the debug draw.

In the end…

In the end I created a large static box (line 13), a small dynamic one (line 14), a static (line 15) and a dynamic (line 16) sphere and I am updating the world at every frame (line 17).

Download the source code, library included.

Rate this post: 1 Star2 Stars3 Stars4 Stars5 Stars (22 votes, average: 4.59 out of 5)
Loading ... Loading ...
Be my fan on Facebook and follow me on Twitter! Exclusive content for my Facebook fans and Twitter followers

This post has 26 comments

  1. jelle

    on February 2, 2010 at 1:39 am

    hey,

    nice, but please show us how to make a triangle in box2d 2.1A or some joint’s those are cool

    jelle

  2. HiddenSpartan

    on February 2, 2010 at 1:53 am

    I fear that you may be writing a third version of this. Right now it’s a 2.1 Alpha release. He’s going to change alot for the final (or so he says), including class names.

  3. Quintus

    on February 2, 2010 at 10:55 am

    @ hiddenspatan

    Who is going to change alot for the final version?

  4. Chris

    on February 2, 2010 at 4:56 pm

    Nice little tutorial.
    That’s how I found this blog some months ago.

    I would be very happy seeing more tutorials making a plattformer using Box2D (I really like to see how you recreate games and making tutorials out of it).

    Basically some basics like how to use premade animations for walkins, how to do jumping and a following cam (so the character stays in center until he reaches the start/end of the level…there the camera will stop and the character can move till the end).

    Otherwise you always do a great job!

  5. Mike F

    on February 2, 2010 at 7:12 pm

    You star. That’s just what I needed.

  6. Vic

    on February 3, 2010 at 9:13 pm

    why is nothing moving? :-)

  7. Vic

    on February 3, 2010 at 9:14 pm

    just ignore my comment :)
    the animation already happened, I was just too late :)

  8. Pullo

    on February 11, 2010 at 2:45 pm

    Yes, i needed that too. Thanks.

  9. Yan

    on February 19, 2010 at 6:33 pm

    I am disapointed.

    Watching the movie in the beggining of the article, it seemed to be so boring that I really didnt feel excited enough to keep reading:

    a) A green ball at left side that keeps eternally stucked at the middle.

    b) a grey square and a grey ball that falls with no physics effect, then touch the green ground and that’s it.

    Do I need a special class package to do that????

  10. anonymous

    on February 22, 2010 at 7:44 am

    #9
    sux to be you

  11. ebbs

    on March 9, 2010 at 10:20 am

    Great tutorial! This has finally got me started with Box2DFlash.

    But how do I get my boxes to act with “real” collision detection, with rotation etc. ?

  12. Moron

    on March 14, 2010 at 1:34 pm

    I follow these exactly and get a blank screen and compile errors.

    I’m almost ready to pay someone to help me through them. No idea what I am doing wrong.

  13. orm

    on May 4, 2010 at 6:44 pm

    I find it ironic that for someone as pro as you Emanuele, you fail to realize how horribly inefficient/idiotic it is to be using division like you are. You should store the physics timestep ahead of time and then use the precomputed timestep every frame instead of passing (1/30) every single frame. Just that one instance may not cause as much as a performance hit, but if this is indicative of the rest of your code… I’m not even gonna start.

    Other than teaching that one bad habit, it is a decent tutorial.

  14. JD

    on May 12, 2010 at 3:21 am

    Nothing happends. No errors but i get a blank screen

  15. wesley

    on June 9, 2010 at 6:40 pm

    i would like to know how to actually make the file :-(

  16. Mathias

    on June 11, 2010 at 5:38 pm

    Hey Emanuele, I’ve come across your site a few time now.
    This must be one of the most basic and working(!) examples of Box2DFlash, congratulations!

    I have one question. Is there a way to ask Box2D if all objects are “resting”? So I could for instance block all UI changes until the simulation has ended (where every object is in it’s final state)…

    Thank you.

  17. }i{

    on August 16, 2010 at 3:22 pm

    Thank you. Great to find such a simple introduction to box2d.

  18. Tony Lukasavage

    on August 19, 2010 at 3:07 pm

    Great tutorial for the Box2D! This really helped me get started. I threw together a simple little demo of my own, modifying the HelloWorld.as in v2.1a so that it does not require the FLA file to run:

    http://savagelook.com/blog/code/box2dflashas3-fun

    Thanks for the head start, I added you to my blogroll!

  19. Jav

    on October 25, 2010 at 10:10 am

    For those who aren’t sure how to make the shapes ‘rotate’ during collision, you need to add density to the fixture.

    my_fixture.density = 1.0;

    To draw a shape besides a box (eg. triangle), replace ‘SetAsBox’ with ‘SetAsVector’ which takes an array of b2Vec2′s.

    Good tut but a bit sad to see simple questions not answered. I’m answering them now because I just spent the time figuring it out, now others hopefully wont have to :)

  20. I am Flash - GaanZa

    on November 5, 2010 at 4:19 am

    [...] to Box2d flash 2.1 you would like to check out: Beginners: http://www.emanueleferonato.com/2010/02/01/box2d-tutorial-for-the-absolute-beginners-revamped/ Complete Walkthrough of HelloWorld Code Example: http://plasticsturgeon.com/?p=295 Physics Based [...]

  21. Top 5 ActionScript 3 Libraries « BobTheCoolGuy

    on January 5, 2011 at 1:31 am

    [...] A powerful physics engine.  this one has a little learning curve, so here is an okay tutorial and a better one that is slightly [...]

  22. altin cilek

    on March 22, 2011 at 4:11 pm

    Thank you. Great to find such a simple introduction to box2d.

  23. altin Çilek

    on March 26, 2011 at 5:14 pm

    Great tutorial! This has finally got me started with Box2DFlash.

  24. Jason

    on May 17, 2011 at 7:11 pm

    not trying to be overly critical (because I’m sure you are doing these tut’s out of the goodness of your heart), BUT it really falls short in explaining anything. And as one person already mentioned, it really lacks in creativity. I would def like to see some textures added to these basic shapes and how to create more complicated shapes and then “skin” them.

  25. Wolfgang

    on August 6, 2011 at 4:28 am

    A comment about all of the negative comments about this not being cool enough… it is “for absolute beginners.” Does that make sense? An overly complicated example would be too much for “absolute beginners” and would defeat the purpose of the article. Personally I think this article is exactly what I needed to get started — thanks a bunch for the great article! I’ll make sure to buy you a coke.

  26. luke

    on September 29, 2011 at 10:05 am

    yup, great tutorial – don’t listen to the haters. box2d has lots of advanced tutorials, but very little documentation on getting started easily – this post provides that in the most focused, simplified way possible. i’d love to see tutorials continuing this with some irregular shapes, different types of ‘bounciness’ to objects, etc. cheers!