0
\$\begingroup\$

Suppose a sprite is attached to a box2d body. And world.destroyBody(b); is getting called then the sprite also get destroyed or it stays there in memory. In my situation lots of box2d bodies are getting created and destroyed and after a delay of few seconds the sprite disappears. Here's the snippet of where body is getting destroyed:

    @Override
public void act(float delta) {
    super.act(delta);
    camera.update();
    world.step(1/60f, 6, 3);
    if (enemy_destroy) {
        Array<Body> bodies = new Array<Body>();
        world.getBodies(bodies);
        for(int i = 0; i < bodies.size; i++) {
            Body b = bodies.get(i);
            if (b.getUserData() instanceof Boolean) {
                world.destroyBody(b);
                b.setActive(false);
            }
        }
    }
}
\$\endgroup\$
1
\$\begingroup\$

No; destroying the body does not automatically destroy the sprite. You have to remove it manually. Assuming you're using LibGDX's Sprite object you simply call dispose() on the texture object linked to the sprite: sprite.getTexture().dispose();. Note that this will render the Texture object unusable!

As for the sprites randomly disappearing: The only reason that I can see that destroying a body would also destroy any sprite attached to it is if the body is holding the last reference to the sprite, so when the body is garbage collected so is the sprite. Although more likely is that there is simply a result of some code you wrote. Try using a debugger to find out why that is happening.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.