4

Hey i'm trying to integrate Box2D and SFML, and my class takes in a Body pointer, which i need to use to get all the points of a fixture so i can form a graphical representation of the body out of them.

How do i get these points?

Griffin
  • 2,399
  • 7
  • 48
  • 83

1 Answers1

10

You can iterate over the fixtures in a body like this:

for (b2Fixture* f = body->GetFixtureList(); f; f = f->GetNext()) 
{
    ....
}

Once you have a fixture you will need to check what kind of shape it has, then cast to that shape type to access the shape data:

b2Shape::Type shapeType = fixture->GetType();
if ( shapeType == b2Shape::e_circle )
{
    b2CircleShape* circleShape = (b2CircleShape*)fixture->GetShape();
    ...
}
else if ( shapeType == b2Shape::e_polygon )
{
    b2PolygonShape* polygonShape = (b2PolygonShape*)fixture->GetShape();
    ....
}

Use GetVertexCount() and GetVertex() to get the vertices from a polygon shape.

Note that vertex positions stored in the fixture are in body coordinates (relative to the body that the fixture is attached to). To get locations in world coordinates, you would have to multiply by the body transform:

b2Vec2 worldPos = body->GetWorldPoint( localPos );
iforce2d
  • 8,194
  • 3
  • 29
  • 40
  • THANK YOU So MUCH. works perfectly now. However i do have a **few questions** (i like to understand the reasoning behind things so i can apply it later): I'm guessing when you attempt to go to nextFixture when there is none it returns with a number that is considered false? And why do i have to CAST (something i would have never thought of) to get the vertices? – Griffin Jul 08 '11 at 05:30
  • say could you take a look at this question too?: http://stackoverflow.com/questions/6621196/how-to-set-centers-of-shapes-fixtures-bodies-in-box2d – Griffin Jul 08 '11 at 07:26
  • The fixture list is a linked list, so each fixture in the list holds a pointer to the next fixture in the list. For the last fixture in the list, the next pointer will be NULL, so the condition 'f' will evaulate to NULL which is the same as false in C. You need to cast because GetShape() only returns a generic b2Shape* pointer, which doesn't know anything about the specific shapes. – iforce2d Jul 08 '11 at 08:29