Reputation: 172
I am learning collision detection and callbacks with box2D. I am trying to implement a very simple thing but my program crashes. I want to destroy b2Body* Drop_object
after it gets collided with another Body.
This is how I have created it:
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;
}
Calling in Timer
function:
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);
}
Destroying In display
Function
if(hide) //hide is a global boolean variable initialized to false
{
world->DestroyBody(Drop_object);
hide = false;
}
And finally the Begincontact function:
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;
}
It takes me to the b2World
DestroyBody
method with an arrow pointing at
je = je->next
Upvotes: 1
Views: 441
Reputation: 2554
You are setting hide to true in any call of BeginContact. I think, you mean this:
if((bodyA == Key_char && bodyB == Drop_object) || (bodyA == Drop_object && bodyB == Key_char))
{
score++;
std::cout << score << std::endl;
hide= true;
}
And, as recomendation:
world->DestroyBody(Drop_object);
Drop_object = nullptr; // To avoid future errors
Answer to comment: I think some bodies do not vanish after collision because you are using one varible for all generated bodies. Suggest next sequence:
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
Upvotes: 2