Ok, this is the first of an tutorial series about Box2D, I'll try to keep post about this cool Physics engine.
Now let's start.
First you need to get you Box2D API, you can get it at http://box2dflash.sourceforge.net/, once you got it make sure you add it to you main API libraries or any folder where you usually put your third party Libs.
You can check the content of the zip file, you can find some fun stuff basics and advanced examples, they call hat the test bed
.
Now all you need is open you Flash CS3 create a new FLA and use the follow class like document class (Make sure you have set your source folder a Library references);
Before you compile let's make clear some basics concept in Box 2D:
Box2D: is a physics engine, it will not draw movieclips for you, heroes or cars, is important to understand that Box2D main duty is to Simulate. It throws the physics and calculus numbers,is not properly a game engine, we use to buid our own game engine and supports its physics. It has a buil-in Debug draw but is just that a Debug.
Bodies and Shapes : Box2d World works with rigid physics bodies, all in Box2D is a body and it has shape associate with it, The body has the variables like the mass the force and the position, the shapes holds the geometry for collisions, friction and , Based in both Box2D build his math and throws the numbers.
Ok now you can get something like:
and lets see the code:
/**
*Author: blog@arturnavi.com
*/
package {
import Box2D.Collision.Shapes.b2CircleDef;
import Box2D.Collision.Shapes.b2PolygonDef;
import Box2D.Collision.b2AABB;
import Box2D.Common.Math.b2Vec2;
import Box2D.Dynamics.b2Body;
import Box2D.Dynamics.b2BodyDef;
import Box2D.Dynamics.b2DebugDraw;
import Box2D.Dynamics.b2World;
import flash.display.Sprite;
import flash.events.Event;
//si quieres compilar esto en Flash builder remueve el siguiente comentario y coloca la clase como main application.
//[SWF(width='400', height='500', backgroundColor='#000000', frameRate='31')]
public class HelloWorld extends Sprite
{
//define nuestro mundo
private var _worldAABB:b2World;
//nuestros numero de iteraciones para que Box resuelve ecaciones en cada paso
private var _iterations:Number =10;
//El numero de pasos
private var _timeSteps:Number =1.0/30.0;
public function HelloWorld(){
createWorld();
createBodies();
}
private function createWorld():void{
//crea la iteracion principal
addEventListener(Event.ENTER_FRAME,update,false,0,true);
//crea el box que compone el mundo principal entre mas grande mejor
var worldBoxAABB:b2AABB = new b2AABB();
worldBoxAABB.lowerBound.Set(-100,-100);
worldBoxAABB.upperBound.Set(100,100);
//variable booleana que nos indica el estado de nuestros elmentos iniciales y que define si nuestros cuerpos dormiran
var sleep:Boolean = true;
//crea nuestro componente de gravedad
var gravity:b2Vec2 = new b2Vec2(0,10);
//inicia nuestro mundo;
_worldAABB = new b2World(worldBoxAABB,gravity,sleep);
//inicia los shapes de debug
var debugDraw:b2DebugDraw = new b2DebugDraw();
var debugSprite:Sprite = new Sprite();
//lo añadimos al stage Box2D usa el graphics api para realizar un aproximacion de la representacion fisica de nuestros cuuerpos
addChild(debugSprite);
debugDraw.m_sprite = debugSprite;
debugDraw.m_fillAlpha=.5;
debugDraw.m_lineThickness=1;
debugDraw.m_drawScale =30.0;
debugDraw.m_alpha=.5;
// con los flags podemos configurar que queremos que nos muestre nuestro debug, para mas info chequea la documentacion de Box.
debugDraw.m_drawFlags = b2DebugDraw.e_shapeBit | b2DebugDraw.e_centerOfMassBit;
_worldAABB.SetDebugDraw(debugDraw);
}
private function createBodies():void{
var body:b2Body;
var bodyDef:b2BodyDef;
var boxDef:b2PolygonDef;
var cirlceDef:b2CircleDef;
//creamos un piso
//creamos la definición del cuerpo para definir su posición en el espacio;
bodyDef = new b2BodyDef();
bodyDef.position.Set(0,15);
//definimos uss propiedades fisicas a traves de una definicion de forma;
boxDef = new b2PolygonDef();
boxDef.SetAsBox(40,1.5);
boxDef.friction =0.3;
boxDef.density=0;
//creamos el cuerpo como tal en nuestro mundo;
body = _worldAABB.CreateBody(bodyDef);
body.CreateShape(boxDef);
body.SetMassFromShapes();
//ahora las paredes izq
bodyDef = new b2BodyDef();
bodyDef.position.Set(0,0);
boxDef = new b2PolygonDef();
boxDef.SetAsBox(1,40);
boxDef.friction =0.3;
boxDef.density=0;
body = _worldAABB.CreateBody(bodyDef);
body.CreateShape(boxDef);
body.SetMassFromShapes();
//ahora las paredes der
bodyDef = new b2BodyDef();
bodyDef.position.Set(14,0);
boxDef = new b2PolygonDef();
boxDef.SetAsBox(1,40);
boxDef.friction =0.3;
boxDef.density=0;
body = _worldAABB.CreateBody(bodyDef);
body.CreateShape(boxDef);
body.SetMassFromShapes();
//creamos formas aleatoriamente
//cubos
for(var i:uint=0;i<5;i++){
bodyDef = new b2BodyDef();
bodyDef.position.x = Math.random() * 10;
bodyDef.position.y = Math.random() * 20;
var w:Number = Math.random() + .5;
var h:Number = Math.random() + .5;
boxDef = new b2PolygonDef();
boxDef.SetAsBox(w,h);
boxDef.density=1;
boxDef.friction = 0.3;
boxDef.restitution = 0.2;
body = _worldAABB.CreateBody(bodyDef);
body.CreateShape(boxDef);
body.SetMassFromShapes();
}
//circulos
for(var j:uint=0;j<5;j++){
bodyDef = new b2BodyDef();
bodyDef.position.x = Math.random() * 10;
bodyDef.position.y = Math.random() * 20;
var r:Number = Math.random() + .3;
cirlceDef = new b2CircleDef();
cirlceDef.density=1;
cirlceDef.radius =r;
cirlceDef.friction = 0.3;
cirlceDef.restitution = 1;
body = _worldAABB.CreateBody(bodyDef);
body.CreateShape(cirlceDef);
body.SetMassFromShapes();
}
}
private function update(evt:Event):void{
_worldAABB.Step(_timeSteps,_iterations);
}
}
}
lines 61-68 : Here is where we crete our debug draw view, if you comment his you will see nothing.
lines 93-95 : Here is where we add all the definitions to our word, this is the standard way to add anything to our Box2D world. As you see we previously defined the body stats then the body shape stats. You can see how this is repeated in all the code to create the walls and the objects.
line 173: Here is our basic loop where we tell to Box iterate and calculate.
Here is the source:
basics_box2d_src
For more detailed functions API, please the Box2d documentation, I ll keep posting more specific tutorials, I hope you like.

Uff, te fajaste con este tuto, he estado 3 dias sin dormir dandole a este motor, lo unico que consegui due un dolor de cabeza, jeje, bueno aparte de crear body's sin poderlos ver, pero cuando los pude ver estaban en desorden y no cordinaban, osea un completo caos.
Gracias por el tuto, SOS GROSO.
Buenas tardes,
Despues de realizar este tutorial, me di cuenta de como funciona el BOX vaya que si es bueno, pero si no es mucho pedir, quisiera saber como le puedo añadir siluetas a las figuras, como ejemplo: quiero que el circulo, se vea como una pelota de futbol. He leido y se que hay que crear el m_clip con la figura y exportarle como clase pero en el box como hago para añadirle la silueta, puesto que he mirado el manual, pero no pude hacerle con el BodyDef.
Gracias y una vez mas !!!SOS GROSO!!!
En el transcurso de esta semana estaré subiendo mas contenido acerca de esto he estado tratando de mudar el material, por favor sean pacientes.
Cheers
Hey, arthur, aquí esta un tuto basado en lo que vos explicaste en el código de arriba, con algunas cosillas de más, como un techo y la posibilidad de crear mas cajitas o mas circulos.
Espero te guste, porque a mi el tuyo me ayudo a realizar esto.
http://www.megaupload.com/?d=Y557TWK2
Auxilio, pues investigando encontre una formilla de unir una forma con el body pero me sale en el centro del body de box 2d con un desfase, aqui adjunto un rar con el codigo me puedes ayudar?
http://www.megaupload.com/?d=YU8LI7CZ
Tu problema es muy sencillo, cuando quieras asignar algo a un cuerpo de Box asegurate que el punto de registro este en 0,0 y en el centro del movieclip, no en la esquina superior izquierda. Felicitaciones por tus ejercicios de Box ya se ve que le estas agarrando el paso.
eeeee.... lo logre ... SOS GROSO!!! EEEEE!, YUPI!!!, ERES EL MAESTRO, EL MASTER, GRACIAS.
MUY BUENO ESTE TUTO. GRACIAS AL MUNDO POR TENER PERSONAS COMO VOS QUE SE INTERESAN EN QUE OTROS APRENDAN.
hola Artur, por fin complete tu primer tutorial completo, ahora pude ingresar las imagenes y darle más vida al futuro juego "algún día sera juego" jeje. Bueno aqui te dejo mi avance, se que andas muy ocupado, pero quisiera saber si me puedes ayudar con la parte de hacer mover el carrito, me sirven links, un código pequeño o documentación. gracias.
aqui te dejo lo que intento hacer, es que se mueva el carrito que veras aqui:
http://www.megaupload.com/?d=M3K0QLG9
que tal artur
tengo severo problemin
resulta que cuando pruebo los archivos del tutorial
me salen muchisimos errores y mirando mas afondo, en la version que descargue de box2d nisiquiera existe la clase b2CircleDef
no entiendo que pueda estar pasando con Box
import Box2D.Collision.Shapes.b2CircleDef;
ya lei un poco mas, pero entonces dice:
Changes
//
List of general API changes from 1.4.3 can be found here
http://box2d.org/forum/viewtopic.php?f=2&t=509
Notes:
-Past users note that b2BoxDef has been replaced by SetAsBox() function in b2PolygonDef
(Refer to any of the PhysTest examples or the manual for more info and usage examples)
-Debug rendering class included, see the constructor in Test.as in the PhysTest project for example usage
-One of the major features of 2.0.0 is the inclusion of CCD, see here for more information:
http://www.box2d.org/manual.html#bullets
//
Hola que tal, tienes razon el API ha cambiado un poco y parte de este contenido esta out-dated, he estado ocupado un poco estos ultimos meses, pero puedes esperar muy pronto un update con los cambios y nuevos tutoriales. Thanks
Thankyou very much, I've found this info very useful!