Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove a body properly in box2d?

Tags:

java

libgdx

box2d

I have a lot of bodies with same BodyDef in Box2D and when I call:

Array<Body> bodies = new Array<Body>();
world.getBodies(bodies);
for(Body b : bodies){
    if(b.getPosition().y < -20f) {
        world.destroyBody(b);
    }
}

it destroys all of the bodies with that BodyDef.

How can I fix that?

like image 466
Mustafa Avatar asked Mar 23 '23 01:03

Mustafa


1 Answers

You're not referencing any BodyDef here.

world.destroyBody(b);

should only destroy body b. Just make sure that your if condition is ok. You could also debug step by step (or put a log inside the if), just to check if the number of bodies destroyed is the same as the times the if condition is true.

like image 83
ssantos Avatar answered Apr 06 '23 10:04

ssantos