S. Russ S. Russ - 3 months ago 26
Android Question

libgdx sensor collision detected but conditional code isn't firing

I have a weird logic error that I am trying to sort through, however I am hitting a wall and can't seem to find my way around it. Perhaps the collective minds here can help!

So, what exactly is happening: I have a disc created in Box2D, as well as a sensor box created in box2D. The logic is simple, if the disc collides with the sensor. you win! The problem is, I can detect the collision between the ball and the sensor, however the condition, you win code isn't firing. Here's the code I am working with.

//instantiating the disc, ground, start platform, and win sensor
disc = createCircleBody("Circle", 20, camera.viewportWidth / 2, 450, 0);
disc.setUserData("disc");

floor = createGround(tmpFloor);
floor.setUserData("floor");

platform = createPlatform(initPlatform);
platform.setUserData("platform");

winSensor = createWinSensor(tmpWinSensor);
winSensor.setUserData("winSensor");

//... Code omitted for clarity ...

world.setContactListener(new ContactListener() {

@Override
public void beginContact(Contact contact) {

Body fixtureA = contact.getFixtureA().getBody();
Body fixtureB = contact.getFixtureB().getBody();

// if the disc and the floor collide.
if((fixtureA.getUserData() == disc.getUserData() && fixtureB.getUserData() == floor.getUserData()) || (fixtureA.getUserData() == floor.getUserData() && fixtureB.getUserData() == disc.getUserData())) {
newDisc.add(tmpDisc);
newDisc.add(tmpPlatform);
bodiesForDeletion.add(disc); // destroy the current disk
}

// if contact is detected between disc and WinSensor
if (fixtureA.getUserData() == winSensor.getUserData() && fixtureB == disc.getUserData()) {

Gdx.app.log("WIN_CONDITION", "You won!"); // This line won't fire.

//TODO: Create alert Box to notify user that they have won the game!
}

Gdx.app.log("beginContact", "between " + contact.getFixtureA().getBody().getUserData() + " and " + contact.getFixtureB().getBody().getUserData() + ".");
}

@Override
public void endContact(Contact contact) {

Body fixtureA = contact.getFixtureA().getBody();
Body fixtureB = contact.getFixtureB().getBody();

Gdx.app.log("endContact", "between " + contact.getFixtureA().getBody().getUserData() + " and " + contact.getFixtureB().getBody().getUserData() + ".");
}

@Override
public void postSolve(Contact arg0, ContactImpulse arg1) {
// TODO Auto-generated method stub
}

@Override
public void preSolve(Contact arg0, Manifold arg1) {
// TODO Auto-generated method stub
}
});


The first collision detection works as intended. The disc collides with the ground box, is deleted and the start platform and a new disc are created outside the world step. I cannot figure out why this code isn't firing.

Answer

It seems like in your if statement

if (fixtureA.getUserData() == winSensor.getUserData() && fixtureB == disc.getUserData()) {

you are missing .getUserData() on your fixtureB.