Box2D:程序在破坏b2Body时崩溃

时间:2013-11-21 21:56:12

标签: c++ opengl box2d collision-detection

我正在学习使用box2D进行碰撞检测和回调。我试图实现一个非常简单的事情,但我的程序崩溃了。我想在与另一个身体发生碰撞后消灭b2Body* Drop_object

这就是我创建它的方式:

b2Body* addDropObj(int x,int y,int w,int h,bool dyn=true)
{
b2BodyDef bodydef;  
bodydef.position.Set(x*P2M,y*P2M);   //Setting body position
if(dyn)
{
        bodydef.type=b2_dynamicBody;  // dynamic body means body will move

}

Drop_object=world->CreateBody(&bodydef);        //Creating box2D body

b2PolygonShape shape;            //Creating shape object
shape.SetAsBox(P2M*w,P2M*h);


dropFixture.shape=&shape;
dropFixture.density=1.0;
dropFixture.restitution = 0.7; 
Drop_object->CreateFixture(&dropFixture);
return Drop_object;
}

调用Timer函数:

    void Timer(int t)
    {

   if (mCounter == 0)
   {
            // rand() % 100 - random value in range 0 - 99
        addBrick(rand() % 100 + 100, 0,10,10);

        mCounter = rand() % MAX_DELAY;
    }
    mCounter--;

        world->Step(1.0/30.0,8,3);

        glutPostRedisplay();
        glutTimerFunc(1000/30,Timer,1);

    }

display函数中销毁

if(hide)                 //hide is a global boolean variable initialized to false
{
world->DestroyBody(Drop_object);
hide = false;
}

最后是Begincontact函数:

    void Callback::BeginContact(b2Contact* contact)
    {


    std::cout << "Begin Contact" << std::endl;

    b2Body* bodyA = contact->GetFixtureA()->GetBody();
    b2Body* bodyB = contact->GetFixtureB()->GetBody();



    if((bodyA == Key_char && bodyB ==  Drop_object) || (bodyA == Drop_object && bodyB     ==  Key_char))
    {   

        score++;
        std::cout << score << std::endl;
    }

    hide= true;

}

我需要b2World DestroyBody方法,箭头指向

je = je-&gt; next

1 个答案:

答案 0 :(得分:2)

您在BeginContact的任何调用中都将hide设置为true。我想,你的意思是:

if((bodyA == Key_char && bodyB ==  Drop_object) || (bodyA == Drop_object && bodyB     ==  Key_char))
{   

    score++;
    std::cout << score << std::endl;
    hide= true; 
}

并且,作为推荐:

world->DestroyBody(Drop_object);
Drop_object = nullptr; // To avoid future errors

回答评论:我认为一些尸体在碰撞后不会消失,因为你对所有生成的身体都使用了一个变量。建议下一个序列:

1) Drop_object=world->CreateBody(&bodydef);
2) Drop_object=world->CreateBody(&bodydef); // First object still falling
3) world->DestroyBody(Drop_object); // Second object contacted, and destoryed
// First object will never be destroyed