AndEngine remove physics body from screen

204 views Asked by At

Can you tell me where is my mistake? In Destroy method on line 'physicsWorld.destroyBody(this.body)' throws exception. I'm using the latest version of AndEngine and Box2D.

public class Asteroid extends Sprite
{
    private PhysicsWorld physicsWorld;
    private PhysicsConnector physicsConnector;
    private Body body;

    public Asteroid(float pX, float pY, ITextureRegion pTextureRegion, VertexBufferObjectManager pVertexBufferObjectManager, PhysicsWorld physicsWorld)
    {
        super(pX, pY, pTextureRegion, pVertexBufferObjectManager);
        this.physicsWorld = physicsWorld;

        final FixtureDef mFixtureDef = PhysicsFactory.createFixtureDef(0, 0f, 0f);
        mFixtureDef.isSensor = true;

        this.body = PhysicsFactory.createCircleBody(physicsWorld, this, BodyDef.BodyType.DynamicBody, mFixtureDef);
        this.physicsConnector = new PhysicsConnector(this, this.body, true, true);
        physicsWorld.registerPhysicsConnector(this.physicsConnector);
        this.body.setLinearVelocity(new Vector2(0, 10));

        this.body.setUserData(this);
    }

    public void Destroy()
    {
        this.physicsWorld.unregisterPhysicsConnector(this.physicsConnector);
        this.body.setActive(false);
        physicsWorld.destroyBody(this.body); // throws Exception ???
        this.detachSelf();
    }
}
1

There are 1 answers

0
GuilhE On BEST ANSWER

You must wait for the physic world cycle to be completed before you make any changes to the world. So the best way to do this is to create an elementsToBeDestroyed List and then remove all the bodies after a world cycle update:

...
physicsWorld = new PhysicsWorld(...) {
    @Override
    public void onUpdate(float pSecondsElapsed) {
        super.onUpdate(pSecondsElapsed);
        for (Body body : elementsToBeDestroyed) {
            destroyBody(body, elementsMap.remove(body).getKey());
        }
        elementsToBeDestroyed.clear();
    }
};  
...

private void destroyBody(final Body body, final IShape mask) {
    if (physicsWorld != null) {
        physicsWorld.unregisterPhysicsConnector(physicsWorld.getPhysicsConnectorManager().findPhysicsConnectorByShape(mask));
        physicsWorld.destroyBody(body);
    }
}