Detecting Collisions

Collision are detected by a class called ContactListener, which, wait for it… listens for contact!

Create a class called WorldContactListener or something else, and make sure that it implements ContactListener as such:

public class WorldContactListener implements ContactListener

You’ll want to make sure to import all of the necessary methods by using the popup that will come up when you hover over the class.

Once you import the methods, your class should look like this:

public class WorldContactListener implements ContactListener
{
    @Override
    public void beginContact(Contact contact)
    {

    }

    @Override
    public void endContact(Contact contact)
    {

    }

    @Override
    public void preSolve(Contact contact, Manifold oldManifold)
    {

    }

    @Override
    public void postSolve(Contact contact, ContactImpulse impulse)
    {

    }

Each on of those methods will let you create logic for when certain things happen, in regards to collisions.

beginContact(Contact contact): gives you information about the contact that occurred at the beginning of the collision.

endContact(Contact contact): gives you information about the contact that occurred after the end of the collision.

preSolve(Contact contact, ContactImpulse impulse): gives you information before the impulse has been calculated, but after the collision has begun.

postSolve(Contact contact, ContactImpulse impulse): gives you information after the impulse has been calculated, but before the collision ends.

There are many ways to check whether a fixture is part of a particular object. In begin contact, you will be able to find which two fixture came in contact and you’ll want to figure out what to do when the play touches a coin, or when a coin touches and enemy or any of the infinite amounts of combinations possible.

Video Lesson