Box2d body, preservation of b2BodyDef, b2Shape, and b2FixtureDef

43 views Asked by At

To create and initialize a b2Body, we need to create a b2BodyDef, b2Shape, and a b2FixtureDef, and we pass these values as pointers to functions.

So I could have a createBody function like this:

b2Body* createBody(b2World& world, b2Vec size, float density, float friction)
{
    b2BodyDef bodyDef;
    bodyDef.type = b2_dynamicBody;
    b2Body* body = world.CreateBody(&bodyDef);

    b2PolygonShape shape;
    shape.setAsBox(size.x, size.y);
    
    b2FixtureDef fixtureDef;
    fixtureDef.shape = &shape;
    fixtureDef.density = density;
    fixtureDef.friction = friction;

    body->CreateFixture(&fixtureDef);

    return body;
}

Here is my question: Do bodyDef, shape, and fixtureDef have to stay in scope?

If not, then this function would be valid, but it seems that Box2d uses pointers to these values, so if they go out of scope, then the program would start to have problems.

There's some code that I've seem that uses similar functions, like this one, which has a function createBox that works just like the function I presented, and I haven't seen any advise about this in the Box2d documentation.

1

There are 1 answers

2
genpfault On

Box2D Overview, Factories and Definitions:

Factories do not retain references to the definitions. So you can create definitions on the stack and keep them in temporary resources.