Box2D: tutorial for the absolute beginners

This is a tutorial about Box2D dedicated to the absolute beginners.

I received a lot of request asking for this, so here we go.

What is Box2D

Box2D is a feature rich 2d rigid body physics engine, written in C++ by Erin Catto.

There is a Flash version called Box2DFlashAS3, but among Flash developers it’s called Box2D as well, that you can download from this link.

Being a Flash porting, we will use AS3 to make our project, instead of C++ as required by the original library.

Once you downloaded and unpacked the zip file in a folder, this is what you will get:

You are now ready to begin

Your first Box2D experiment

Start Flash and create a new AS3 Flash file and call it (example) demo.fla. Save it in the same folder you used to unzip Box2D package. Also in your properties panel assign the Class name to (example) demo, this way:

Now create a new actionscript file, call id demo.as and save it in the same folder.

Your folder now should look this way:

it’s time to edit demo.as

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
60
61
62
63
package {
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.utils.Timer;
	import flash.events.TimerEvent;
	import Box2D.Dynamics.*;
	import Box2D.Collision.*;
	import Box2D.Collision.Shapes.*;
	import Box2D.Common.Math.*;
	public class demo extends Sprite {
		public var the_world:b2World;
		var time_count:Timer=new Timer(1000);
		public function demo() {
			var environment:b2AABB = new b2AABB();
			environment.lowerBound.Set(-100.0, -100.0);
			environment.upperBound.Set(100.0, 100.0);
			var gravity:b2Vec2=new b2Vec2(0.0,10.0);
			the_world=new b2World(environment,gravity,true);
			var debug_draw:b2DebugDraw = new b2DebugDraw();
			var debug_sprite:Sprite = new Sprite();
			addChild(debug_sprite);
			debug_draw.m_sprite=debug_sprite;
			debug_draw.m_drawScale=30;
			debug_draw.m_fillAlpha=0.5;
			debug_draw.m_lineThickness=1;
			debug_draw.m_drawFlags=b2DebugDraw.e_shapeBit;
			the_world.SetDebugDraw(debug_draw);
			var final_body:b2Body;
			var the_body:b2BodyDef;
			var the_box:b2PolygonDef;
			the_body = new b2BodyDef();
			the_body.position.Set(8.5, 13);
			the_box = new b2PolygonDef();
			the_box.SetAsBox(8.5, 0.5);
			the_box.friction=0.3;
			the_box.density=0;
			final_body=the_world.CreateBody(the_body);
			final_body.CreateShape(the_box);
			final_body.SetMassFromShapes();
			addEventListener(Event.ENTER_FRAME, on_enter_frame);
			time_count.addEventListener(TimerEvent.TIMER, on_time);
			time_count.start();
 
		}
		public function on_time(e:Event) {
			var final_body:b2Body;
			var the_body:b2BodyDef;
			var the_box:b2PolygonDef;
			the_body = new b2BodyDef();
			the_body.position.Set(Math.random()*10+2, 0);
			the_box = new b2PolygonDef();
			the_box.SetAsBox(Math.random()+0.1,Math.random()+0.1);
			the_box.friction=0.3;
			the_box.density=1;
			final_body=the_world.CreateBody(the_body);
			final_body.CreateShape(the_box);
			final_body.SetMassFromShapes();
		}
		public function on_enter_frame(e:Event) {
			the_world.Step(1/30, 10);
		}
	}
}

Lines 2-5: some commons Flash libraries used to make the demo

Lines 6-9: Box2D libraries… it’s not that important at the moment to know everything about them… they’re just some libraries

Line 11: Declaring the_world variable, b2World type. b2World is the the main object to deal with the Box2d engine. It stores all the joints and bodies, handles listeners and is responsible for stepping through the simulation.

Line 14: Declaring the_environment, b2AABB type. The physics environment generated by Box2D is not infinite, and b2AABB is the container of such environment. Think about it as a bounding box. Inside this bounding box, the world is ruled by Box2D physics.

Lines 15-16 : Defining the upper and lower corners of the environment bounding box, in meters. 1 meter = 30 pixels. So our box has sides made by 6000 pixels. They’re pretty too much for a single-screen project, but if you are using scrolling, it could be useful to set up a big environment. For more information about pixels and meters refer to Understanding pixels and meters with Box2D and how to select an object with mouse – part 2.

Line 17: Declaring gravity variable, b2Vec2 type. b2Vec2 is a vector with x and y components.

Line 18: Starting up the world: the constructor has three parameters: environment, the worldAABB bounding box, gravity the world gravity vector, and a boolean set to true to improve performance by not simulating inactive bodies.

And now you created the world. Next time I’ll explain the rest of the script

Anyway, this is the result

And this is the source code to download.

I hope this will help you start playing with Box2D.

Rate this post: 1 Star2 Stars3 Stars4 Stars5 Stars (43 votes, average: 4.60 out of 5)
Loading ... Loading ...
If you found this post useful, please consider a small donation.
» Flash Templates provided by Template Monster are pre-made web design products developed using Flash technology.
They can be easily customized to meet the unique requirements of your project.

40 Responses to “Box2D: tutorial for the absolute beginners”

  1. Superdean on January 28th, 2009 12:35 am

    YES!
    finally a box 2d tutorial i can understand!
    this actually might make me migrate to AS3…

  2. Yowan on January 28th, 2009 3:37 am

    Awesome!!
    Thanks a lot!

  3. Shival on January 28th, 2009 11:03 am

    You are really the rockstar of programming

  4. Shival on January 28th, 2009 11:06 am

    make it PROgramming

  5. Xavi on January 28th, 2009 6:57 pm

    thanx emanuele for making a tut for Box 2D that is for begginers
    i haven’t started AS3 yet, but i think this will help…
    do u have a beggining AS3 tutorial

  6. Prankard on January 29th, 2009 4:04 am

    Very basic for my taste. But you can’t satisfy everyone :)
    Glad you got a good response from your other users.
    Keep up the more advanced tutorials too.

  7. Xodus on January 29th, 2009 1:58 pm

    XD

  8. FrozenHaddock on January 29th, 2009 2:03 pm

    Excellent!

    I shall be closely following both the basic Box2D tutorials tonight and start playing around with them!

  9. Koczo on February 2nd, 2009 4:33 pm

    It looks great, but when i’m trying to open “demo.fla” file in Adobe Flash CS3, I got the message “Unexpected file format”. Do you know why?

  10. Fabien Millerand on February 23rd, 2009 3:43 am

    Hi,

    I wanted to know if there was an easy way to add a texture to those ‘boxes’..
    Thx
    Fabien

  11. lol on March 20th, 2009 6:59 pm

    uuuh, yeeeah, that’s so PROOO Mr. PROgrammer

  12. Tobias C. on April 16th, 2009 4:55 pm

    Thanks a lot!!!!

  13. Fighterlegend on April 25th, 2009 8:47 pm

    Can you put it in a Flash CS3 format?

    Or do I NEED Flash CS4?

    If I do, that would suck! :(

  14. Destruction on May 4th, 2009 6:02 am

    Nice guide, might play around with it sometimes.
    Also, hi Fighterlegend!

  15. Thempc on May 28th, 2009 2:09 pm

    to Fighterlegend:
    no you do not NEED CS4 for this,
    this can also be done in CS3 with ease.

    PS: awesome tutoial 5/5

  16. Androoo on August 6th, 2009 2:26 pm

    Why don’t you reply to peoples questions?

  17. Mokey on August 8th, 2009 5:20 am

    Nice tutorial. I’m still learning as3 and this will be very useful. Thanks!

  18. cyancdesign on August 27th, 2009 4:24 am

    This one help me start off on the right foot. And all your other tutorials are awesome! I was able to expand on this to turn the boxes into dynamic falling text.
    (^_^)// Cheers.

  19. shuping chen on August 29th, 2009 5:16 am

    Thank you very much.^_^

  20. Chris on October 13th, 2009 2:35 am

    Thanks for these, really finding them useful.

    One thing though, you mentioned that 1 meter = 30 pixels… is that a default or do you have to set that ratio somewhere in the code?

    Thanks again.

  21. Efe on October 21st, 2009 6:26 am

    Thank you for the lovely tutorial, its beyond amazingly useful. As a low to mid-level Flash progrommer / animator, getting a handle on the Box2D stuff through just the examples is actually quite difficult (and not helped by the slightly more ambiguous naming conventions it uses)

    But seriously, amazing stuff. Thanks :)

  22. Sam on November 17th, 2009 8:37 pm

    I don’t seem to have flash, to create a new AS3, I need help. Can you give me a link?

  23. bubloobasu on December 22nd, 2009 7:47 am

    Can u pls explain the rest of the script

  24. Sucks man... on January 8th, 2010 3:37 am

    Errm.PART 2!!!!!!!!!!!!!!!!!!!!!?????????????????

  25. No it doesn't! on January 8th, 2010 3:39 am
  26. clayton on January 25th, 2010 3:34 pm

    i followed the directions exactly as listed, however when i try to run the program, it gives me a bunch of errors starting with:

    1046: Type was not found or was not a compile-time constant: b2World.
    1046: Type was not found or was not a compile-time constant: b2AABB.
    1046: Type was not found or was not a compile-time constant: b2Vec2.

    anyone have any ideas?

  27. Rackdoll on January 27th, 2010 2:48 pm

    @clayton

    your classpaths arent correct configured..
    these errors happen when flash or your code editor cannot find the class you are trying to use..
    So check your linkage to the classes and try again :)

    it also helps to get a basic understanding of AS3.0 and OO before you start a tutorial like this one.

    ;)

  28. Angry on January 28th, 2010 5:40 am

    ok. I tried this and it was an epic fail.

    The idiots who made Box2d decided to randomly change the whole thing! The box2d looks nothing like the screenshots you had. Could you plz make a new tutorial?! thanks.

  29. Xalvez on January 28th, 2010 11:12 am

    I got the same error with #26.
    Help pls ><

  30. Sam on February 6th, 2010 4:34 pm

    Hi, guys.

    You need to have the following in order to successfully run Demo.fla.

    1. Adobe Flash CS4
    2. Box2DFlashAS3_2.0.2

    Download Box2DFlashAS3_2.0.2 in here.

    http://sourceforge.net/projects/box2dflash/files/

    If you have any questions, ask. :-)

    Thank you for the great tutorial, Emanuel! You rock!

    Sam

  31. merve on February 13th, 2010 9:43 pm

    hello,
    i liked very much the scene i see in the last animation screen.

    now i want to ask whether it is possible to write an application without using flash development environment? i am a newbee in software developing but i like flash applications too. but i am a student and no have money for flash development environment.
    is there a compiler for action script desperate from flash development environment?
    i googled a bit but find nothing.

    thanks for tutorial and any possible advises.

  32. Gab on February 14th, 2010 3:55 am

    I tryed this code with Adobe Flash IDE CS4 : It’s okay.

    When I try with an AS3 project with Flash Develop, debugDraw doesn’t display any objects.

    I use : FlashDevelop 3.0.6/Box2D 2.0.2/Flex 3.4

  33. Tim on February 23rd, 2010 2:25 pm

    Learning AS3 and your tutorial is an awesome way to experiment. Really one of the best sites I’ve found about Flash, Actionscript, and games. Thanks for sharing your knowledge.

Leave a Reply




Trackbacks

  1. Emanuele Feronato on January 29th, 2009 12:20 pm

    [...] Box2D: tutorial for the absolute beginners [...]

  2. Weekly Shared Items - 30. January, 2009 « toxin 2.0 on January 30th, 2009 9:53 am

    [...] Box2D: tutorial for the absolute beginners [...]

  3. A smart way to manage sleeping objects with Box2D : Emanuele Feronato on February 18th, 2009 11:04 am

    [...] you followed Box2D: tutorial for the absolute beginners, then you know you can put some object to “sleep” to improve performance by not [...]

  4. Erase Box, a Box2D game made with my tutorials : Emanuele Feronato on February 21st, 2009 1:13 pm

    [...] a mix of your tutorials about “Box2D for absolute begginers” and “Totem Destroyer Prototype“. I also added some other features, such as the [...]

  5. AS3 Flash Physics Engine Box2D | [mck] on May 1st, 2009 11:15 am

    [...] Boy Wonder!!) Emanuele Feronato (an Italian PROgrammer) has written an extremely useful tutorial: box2d tutorial for the absolute beginners/. This one is a very good starting [...]

  6. Box2DFlash - Falling Text | Cyan[c] Design on August 26th, 2009 5:54 am

    [...] want to give yet another shout out to Emanuele Feronato. If you are looking at this code, and are completely lost, he has EXCELLENT tutorials to get you [...]

  7. Box2D tutorial for the absolute beginners – revamped : Emanuele Feronato - italian geek and PROgrammer on February 2nd, 2010 1:00 am

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

flash games company