Question

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.

Was it helpful?

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
}

OTHER TIPS

To add to what Mattias said, I do the same thing he does, by pushing objects to the ToBeRemoved list.

and I have an actor class for each graphical sprite in the scene, here is some code:

public class Actor
{
    protected var m_body:b2Body;
    protected var m_sprite:DisplayObject;

    public function Actor(body:b2Body, sprite:DisplayObject)
    {
        this.m_body = body;
        this.m_sprite = sprite;
    }

    public function destroy():void
    {
        // remove sprite
        m_sprite.parent.removeChild(m_sprite);

        // remove physical body
        GlobalVars.world.DestroyBody(m_body);
    }
}

and whenever I want to destroy an object, I just call the Actor's destroy method.

Note that this class' fields are protected so we can extend it by child actors.

This way, it works smoothly.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top