Dawesign
Dawesign

Reputation: 763

Box2D collision won't call my own CollisionListener

I want to use Box2Ds collision detection to check if the player collides with something. So I made a class and implemented the class CollisionListener so I can use the methods beginContact() to check if the player collides with something. For now I just wanted to print in the console if this methods does even work. It does not. Here is my code:

I made a class MyCollisionListener which implements CollisionListener like so:

In the class Play:

// ...
private World world;
private ContactListener contactlistener;

public Play(GameStateManager gsm) {
    super(gsm);

    world = new World(new Vector2(0, -1), true);
    world.setContactListener(contactlistener);
// ...

My class MyContactListener:

public class MyContactListener implements ContactListener {

    public MyContactListener() {}

    @Override
    public void beginContact(Contact contact) {
        System.out.println("Contact!");
    }

    @Override
    public void endContact(Contact contact) {
        // TODO Auto-generated method stub
    }


    @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
    }
}

For some reason a collison won't call the method beginContact in MyCollisionListener. Why?

Upvotes: 0

Views: 118

Answers (1)

cfrick
cfrick

Reputation: 37073

Iff your code there is not lacking some steps, due to shortening for examples sake, you are passing null in as contact listener:

private World world;
private ContactListener contactlistener;

public Play(GameStateManager gsm) {
    super(gsm);
    world = new World(new Vector2(0, -1), true);
    contactlistener = new MyContactListener(); // XXX
    world.setContactListener(contactlistener);

Upvotes: 2

Related Questions