3. Polígonos - nelsonmoreno/Box2d GitHub Wiki

Box2d soporta la creación de círculos, rectángulos y cuadrados, así como polígonos más complejos.

Circulo

Para crear un circulo debemos definir ademas el radio del objeto:

this.fixDef = new b2FixtureDef;
this.fixDef.density = 1.0;
this.fixDef.friction = 0.5;
this.fixDef.restitution = 0.2;

this.bodyDef = new b2BodyDef;
this.bodyDef.type = b2Body.b2_dynamicBody;
this.fixDef.shape = new b2CircleShape(radius);

this.bodyDef.position.x = x;
this.bodyDef.position.y = y;
this.world.CreateBody(this.bodyDef).CreateFixture(this.fixDef);

Cuadrado

Para crear un rectángulo debemos definir ademas la altura y el ancho del objeto:

this.fixDef = new b2FixtureDef;
this.fixDef.density = 1.0;
this.fixDef.friction = 0.5;
this.fixDef.restitution = 0.2;

this.bodyDef = new b2BodyDef;
this.bodyDef.type = b2Body.b2_dynamicBody;
this.fixDef.shape = new b2PolygonShape;
this.fixDef.shape.SetAsBox(halfWidth, halfHeight);

this.bodyDef.position.x = x;
this.bodyDef.position.y = y;
this.world.CreateBody(this.bodyDef).CreateFixture(this.fixDef);

Polígono

Según la definición de Box2d del poligono "Polygon shapes are solid convex polygons. A polygon is convex when all line segments connecting two points in the interior do not cross any edge of the polygon. Polygons are solid and never hollow. A polygon must have 3 or more vertices. You must create polygons with a counter clockwise winding (CCW)"

Los polígonos deben ser convexos, no deben tener menos de 3 y no más de ocho vértices, ademas los vértices deben ser definidos en sentido de las manecillas del reloj.

this.fixDef.density = 1.0;
this.fixDef.friction = 0.5;
this.fixDef.restitution = 0.2;

this.bodyDef = new b2BodyDef;
this.bodyDef.type = b2Body.b2_dynamicBody;
this.fixDef.shape = new b2PolygonShape;

// entity.points == [{x: 0, y: 0}, {x: 1, y: 0}, {x: 0, y:2}]
var points = [];

for (var i = 0; i < entity.points.length; i++) {
    var vec = new b2Vec2();
    vec.Set(entity.points[i].x, entity.points[i].y);
    points[i] = vec;
}

this.fixDef.shape.SetAsArray(points, points.length);

this.bodyDef.position.x = x;
this.bodyDef.position.y = y;
this.world.CreateBody(this.bodyDef).CreateFixture(this.fixDef);

Hay que tener muy presente que en Box2d la posición de un circulo o de un cuadrado es siempre el centro, sin embargo si el objeto es un polígono dicha afirmación no se cumple en muchos casos, lo mismo sucede con el centro de masa.

En Box2d un cuerpo (body) puede tener varias formas, dicho de otro modo a un cuerpo le podemos anexar varias formas (pegar un polígono a otro), por lo que de esta manera podemos construir objetos mas complejos y de hecho cóncavos.

this.fixDef.density = 1.0;
this.fixDef.friction = 0.5;
this.fixDef.restitution = 0.2;

this.bodyDef = new b2BodyDef;
this.bodyDef.type = b2Body.b2_dynamicBody;
this.fixDef.shape = new b2PolygonShape;

// entity.polys ==  [[{x: -1, y: -1}, {x: 1, y: -1}, {x: 1, y: 1}, {x: -1, y: 1}], // box
                      [{x: 1, y: -1.5}, {x: 2, y: 0}, {x: 1, y: 1.5}]  // arrow]

for (var j = 0; j < entity.polys.length; j++) {
    var points = entity.polys[j];
    var vecs = [];
    for (var i = 0; i < points.length; i++) {
        var vec = new b2Vec2();
        vec.Set(points[i].x, points[i].y);
        vecs[i] = vec;
    }
    this.fixDef.shape = new b2PolygonShape;
    this.fixDef.shape.SetAsArray(vecs, vecs.length);
    body.CreateFixture(this.fixDef);
}