Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set centers of shapes/fixtures/bodies in Box2D

Hey i'm trying to integrate SFML and Box2D, and SFML has made setting centers for sprites, shapes, etc. very easy. Box2D, on the other hand, I'm having trouble with as i can't figure out how to set or even find the center of a shape or fixture.

It seems to me that when adding vertices manually to a b2_PolygonShape the center is set to the first vertex in the vertex array, but the results are very different when using the shortcut functions SetAsBox() or any other SetAs__(). The Center is the middle of the shape, or half extent(s) of the box/shape.

I need to commonize box2D's and SFML's centering system, but i can't figure out how the local coordinate systems work for objects.

How do I set/get the centers of the many objects such as shapes, fixtures, bodies, etc. in Box2D?

like image 917
Griffin Avatar asked Jul 08 '11 07:07

Griffin


3 Answers

Ok I realized that SFML and Box2D really weren't all that different, but i just wasn't thinking about how shapes are made/ rendered correctly in world coordinates.

Unless otherwise specified, (0,0) is always used as the refrence point/ center of the object when its position is being moved around/ drawn, and each vertex is drawn in relation to that point.

the SFML tutorial was a bit confusing as it said setting the center of a shape/sprite was the offset from the top left corner of the object, not (0,0).

like image 164
Griffin Avatar answered Oct 19 '22 06:10

Griffin


I think that with box2d you are responsible of making the 'centroid' of the polygon coincide with the position of your body. Basically what you have to do is something like this.

  • Compute the centroid of your list of vertices (b2vec)

  • Shift the vertices by -centroid.

Box2d provides the necessary functions to help you with this task. What happens with SetAs__ is that the centroid is (0,0) and the polygon is created symmetrically around the center of the body.

like image 36
crisbia Avatar answered Oct 19 '22 07:10

crisbia


I'll give it another try. I'm pretty sure I can help you but I don't understand your question completely.

A body has a Position (b2Vec2) in the world.
A body has b2Fixtures (density, friction, restitution, shape, etc...)
The b2PolygonShape has vertices and mass data. Those vertices are relative to the body position.

Example vertices for a b2PolgygonShape (rectangle, size: 1 meter * 1 meter)

(-0.5f, -0.5f)  // left  upper corner
( 0.5f, -0.5f)  // right upper corner
( 0.5f,  0.5f)  // right lower corner
(-0.5f,  0.5f)  // left  lower corner

Keep in mind you can't set the vertices yourself! You have to pass them to

b2PolgygonShape::Set(b2Vec2 *vertices, int count);

This method will compute the mass data, depending on the vertices.

like image 1
Martijn Courteaux Avatar answered Oct 19 '22 06:10

Martijn Courteaux