Dynamic objects passing through static objects

For some reason my objects don't seem to be colliding if they're created within another class. Is there something simple that i'm missing?

StackBox.cpp

Code: Select all

StackBox::StackBox(float x, float y, b2World* pWorld){
    world = pWorld;

    b2BodyDef stackBoxBodyDef;
    stackBoxBodyDef.type = b2_dynamicBody;
    stackBoxBodyDef.position.Set(x, y);
    stackBody = pWorld->CreateBody(&stackBoxBodyDef);

    b2PolygonShape stackBox;
    stackBox.SetAsBox(1.0f, 0.1f);

    b2FixtureDef fixtureDef;
    fixtureDef.shape = &stackBox;
    fixtureDef.density = 1.0f;
    fixtureDef.friction = 0.3f;
    fixtureDef.restitution = 0.5f;

    stackBody->CreateFixture(&fixtureDef);
}

Player.cpp

Code: Select all

Player::Player(){
    b2Vec2 gravity(0.0f, -10.0f);
    world = new b2World(gravity);
    world->SetAllowSleeping(true);

    maxStackSize = 4;
    createStack(destCluster);

    groundBodyDef.position.Set(0.0f, 0.0f);
    groundBody = world->CreateBody(&groundBodyDef);
    groundBox.SetAsBox(10.0f, 1.0f);
    groundBody->CreateFixture(&groundBox, 1.0f);
}

Player::~Player(){
    delete world;
}

void Player::createStack(PCluster* destCluster){
    float heightIndex = 4;

    for(int i = 0; i < maxStackSize; i++)
    {
        StackBox box(0, heightIndex, world, g_clusterArray[PlayerAssets::g_pizzaIndex], destCluster);
        vStack.push_back(box);
        heightIndex += 0.4;
    }
}

The player is a single class and creates 4 StackBox objects in this instance. The StackBox renders fine and the gravity works as needed but it seems to pass through my ground object. I have tested and the ground object is still in the scene and there are 5 objects. If I add the ground object code to after the StackBox initialisation, they seem to recognise the ground being there but pass through a couple of seconds later.
You are looking at the debug draw display right?
There doesn't seem to be anything obviously wrong with this code, although I would advise storing the boxes in a vector of StackBox* rather than StackBox.
I would guess the problem is somewhere else, other than in this code you've shown so far.
For example, the original StackBox instances created in the loop in createStack will be destroyed at the end of each loop iteration. It depends on what the StackBox class destructor does, as to whether the pointers to the b2Body it holds will still be valid.

Original thread: https://box2d.org/forum/viewtopic.php?t=9963