# Physics on Flash. Box2D Engine

Fast, convenient and powerful open source physics engine. Under the cut - links, a small tutorial and an example of use.

#### References

The Box2D project itself is located at this address - http://www.box2d.org/ , where you can read about its capabilities, chat on the forum, etc.
AS3 port was made from it, the home page is http://box2dflash.sourceforge.net/ . There is a clip on it showing the capabilities of this engine. By the way, all with Friday)

#### Usage (most basic)

1. We create a “world”, all calculations take place only within this world, an object that goes beyond its borders falls out of the calculations. So what we do with a margin (WIDTH and HEIGHT - window sizes):
```      // world bounding box       var worldAABB : b2AABB = new b2AABB();       worldAABB.lowerBound.Set(-WIDTH, -HEIGHT);       worldAABB.upperBound.Set(2*WIDTH, 2*HEIGHT);                    // create world. zero gravity + use "sleeping" for objects       m_world = new b2World(worldAABB, b2Vec2.Make(0, 0), true); * This source code was highlighted with Source Code Highlighter.```

2. Add the object to the world.
The object is characterized by two components.
The first is the geometric representation of the object (its “surface”). Each object can consist of several shapes, which are convex polygons or circles (but nothing prevents to expand the basic shape and write your own).
It also sets the density, friction, etc.
```      // shape definition       var bodyShapeDef : b2PolygonDef = new b2PolygonDef();       // as rectangle       bodyShapeDef.SetAsBox(w/2, h/2);       // density       bodyShapeDef.density = 1.0;       // friction       bodyShapeDef.friction = 0.3; * This source code was highlighted with Source Code Highlighter.```

The second is the object itself, its position, mass, moment of inertia, etc.
Description of the object:
```      // object definition       var bodyDef : b2BodyDef = new b2BodyDef();       // world position       bodyDef.position.Set(xc, yc);       // linear "friction with world"       bodyDef.linearDamping = 0.3;       // angular "friction with world"       bodyDef.angularDamping = 0.3; * This source code was highlighted with Source Code Highlighter.```

Creation of an object (it is automatically registered in the world). Assignment of a previously created geometric representation to him, and (very conveniently) automatic calculation of all physical parameters based on its density and shape.
```      // create object from definition       var body : b2Body = m_world.CreateBody(bodyDef);       // create object shape from shape definition       body.CreateShape(bodyShapeDef);       // calculate mass, center of mass and inertia       // based on shape       body.SetMassFromShapes(); * This source code was highlighted with Source Code Highlighter.```

There is a third (optional) component of the object - its presentation on the screen. At the initial stages of development, you can use the b2DebugDraw class, which shows all the objects, the relationships between them, etc. But how to connect, for example, your own MovieClip and a physical object?
The most commonly used practice is to use the userData field of the created object.
Remember the screen representation in this field:
```      // save screen object in userData field       body.SetUserData(bodyDisplayObject); * This source code was highlighted with Source Code Highlighter.```

3. Emulation
Everything is simple here. The world has a Step function, which takes the step time in milliseconds seconds and the number of iterations that need to be done at this step. After emulation, we go through all the objects of the world, look, if the userData field contains a screen representation, then we update the position / rotation of this view in accordance with the fields of the physical object.
```   // calculate physics    // using 10 steps of physics for each frame    m_world.Step(dt, 10);    // loop for all physic objects    for(var body : b2Body = m_world.GetBodyList(); body; body = body.GetNext())    {     // if userData is not a shape, then skip this object     if(!(body.GetUserData() is Shape))      continue;     // update screen object to be equal physical object          body.GetUserData().x = body.GetPosition().x;     body.GetUserData().y = body.GetPosition().y;     body.GetUserData().rotation = body.GetAngle() * 180.0 / Math.PI;    } * This source code was highlighted with Source Code Highlighter.```

#### Example

Wrote a small application in an attempt to create a snake. 80 rectangles are connected in pairs by RevoluteJoints, with a rotation limit of + -20 degrees. When the mouse moves the head segment of the snake receives an impulse in the direction of the cursor, as a result, the entire snake creeps. Also in the world objects are arranged so that there is something to crawl around.
On click, the application switches between its own drawing and b2DebugDraw.
application - http://www.rexxar.ru/snake/
sources - http://www.rexxar.ru/snake/src.zip

Another test - shows the points of collisions. By clicking, a new rectangle is created and falls to the ground.
application - http://www.rexxar.ru/phys/ .

#### Conclusion

Analysis of the engine and writing examples took literally several hours, a very simple, convenient, fast and powerful tool for emulating physics. I will use it.