0
votes

I'm super new to libgdx and java.

I'm extending the Simple App game from libgdx's documentation. I made the raindrops and the bucket bodies, and also made a "ground" body.

The tutorial handles collision detection this way:

Iterator < Body > iter = raindrops.iterator();
while (iter.hasNext()) {
    Body raindrop = iter.next();
    if (raindrop.y + 64 < 0) {
        dropped++;
        iter.remove();
    }
    if (raindrop.overlaps(bucket)) {
        dropSound.play();
        catched++;
        iter.remove();
    }
}

And it worked as intended, but since I made every raindrop a body, I can't use the overlaps() function any more, so I had to use box2d's collision detection:

Iterator < Body > iter = raindrops.iterator();
while (iter.hasNext()) {
    Body raindrop = iter.next();

    world.setContactListener(new ContactListener() {

        @Override
        public void beginContact(Contact contact) {
            Fixture fixtureA = contact.getFixtureA();
            Fixture fixtureB = contact.getFixtureB();
            if ((String) fixtureA.getBody().getUserData() == "bucket" && (String) fixtureB.getBody().getUserData() == "drop" || (String) fixtureA.getBody().getUserData() == "drop" && (String) fixtureB.getBody().getUserData() == "bucket") {
                //csepp és vödör ütközik
                dropSound.play();
                catched++;
                iter.remove();

            }
            if ((String) fixtureA.getBody().getUserData() == "ground" && (String) fixtureB.getBody().getUserData() == "drop" || (String) fixtureA.getBody().getUserData() == "drop" && (String) fixtureB.getBody().getUserData() == "ground") {
                //csepp és föld ütközik
                dropped++;
                iter.remove();
            }
        }

        @Override
        public void endContact(Contact contact) {}

        @Override
        public void preSolve(Contact contact, Manifold oldManifold) {
            // TODO Auto-generated method stub

        }

        @Override
        public void postSolve(Contact contact, ContactImpulse impulse) {
            // TODO Auto-generated method stub

        }

    });
}

My main problem is, that iter.remove(); doesn't remove the correct raindrop. Upon collision it removes the newest raindrop, not the one that collided with the bucket.

Also, the box2d body doesn't get removed.

How can I do this? Thanks!

1

1 Answers

2
votes

Don't save Strings as the UserData, save a reference to your entities instead (raindrop, bucket...). Then you will know which Raindrop exactly caused the collision and you can remove exactly that one. The Body will be removed via World.destroyBody(...).

BUT you cannot call that method while the physics step is in processing. That means, you cannot use it directly in your collision callbacks.

Instead: Put the bodies to be removed in a temporary list and run through this list after the physics step and remove them.