Search code examples
flashactionscript-3garbage-collectionbox2dphysics-engine

Box2D Flash, Destroying bodies


This is a problem I have been wanting to solve for a while, although I can never find a way to fix it. I think I may be missing something, but I can't seem to find what.

I'm trying to destroy bodies from the b2World, I've seen on various tutorials that when they destroy an object in box2d with debug draw on, the shape gets destroyed too. For some reason when I do:

world.DestroyBody(_body) it doesn't seem to do anything. The shape stays on the screen.

Has anybody had this problem before? It makes me worry because after a while with playing the game, all the objects which I want to destroy remain on the screen and still register collisions which really lag up the game.

Any help would be much appreciated,

Thanks,
Will

EDIT: [RESOLVED] Thanks guys, that makes perfect sense.


Solution

  • I have had this problem myself in some projects. I think it happens when you are trying to remove a body that is "in use" by the Box2D engine. I have solved it by adding the bodies i want to destroy to a list and then destroy them before the the next render.

    // add body to list if it should be removed
    if(shouldRemoveBody)
    {
        _removeList.push(bodyToRemove);
    }
    
    // start next render with a check
    if(_removeList.length > 0)
    {
        // remove all bodies in list
    }