3
votes

I'm using AndEngine to create a game with box2d extension. I want to implement a condition that when two bodies collide, they should be removed or respawned. Initially I tried using

if(sprite1.collidesWith(sprite2))
// remove the sprites

but this doesnt seem to help because the sprites are attached to their respective bodies. I also tried using contactListener as follows:

bodyA=getFixtureA().getBody();
bodyB=getFixtureB().getBody();

and then later

if(bodyA!=null && bodyB!=null)
// remove the bodies

but that crashed the game. Does anybody know a better way of doing it?

2
If my answer helps you than please dont forgot to accept my answer and up vote me it will be much appreciated . Thanks :)SALMAN

2 Answers

4
votes

So there's some stuff out there about Collision but it took me quite awhile to figure out how to remove the objects based on collision. So decided to do a quick tutorial to try and help other people out. The key is that in Box2D you cannot delete the body in the collision handler and need to do something to mark it for deletion to be handled on the next update. (might be better ways but this works and gets the job done)

Here is link for a very nice tutorial.

Box2D Collision and Removal

This will surely help you to get your work done.

Thanks :)

2
votes

If the Sprite collision actually occurs, you can remove the bodies as well at the same time:

mPhysicsWorld.getPhysicsConnectorManager().findPhysicsConnectorByShape(pSprite);