I am developing a game using LibGDX and Box2D, today I implemented coins as dynamic bodies and wanted to make player gain gold by reading contact through my ContactListener.
So far everything was working, here is my example of player colliding with ladder object in the ContactListener class:
@Override
public void beginContact(Contact contact) {
Fixture fixA = contact.getFixtureA();
Fixture fixB = contact.getFixtureB();
int cDef = fixA.getFilterData().categoryBits | fixB.getFilterData().categoryBits;
switch (cDef) {
case Constants.PLAYER_BIT | Constants.LADDER_BIT:
if (fixA.getFilterData().categoryBits == Constants.PLAYER_BIT) {
((HeroKnight) fixA.getUserData()).climbLadder();
}
else {
((HeroKnight) fixB.getUserData()).climbLadder();
}
However, strangely the coin collision only works one way.
case Constants.PLAYER_BIT | Constants.COIN_BIT:
if (fixA.getFilterData().categoryBits == Constants.PLAYER_BIT) {
((CoinTest) fixB.getUserData()).use();
}
When I add the else statement, as seen below, the game keeps crashing with java.lang.NullPointerException.
case Constants.PLAYER_BIT | Constants.COIN_BIT:
if (fixA.getFilterData().categoryBits == Constants.PLAYER_BIT) {
((CoinTest) fixB.getUserData()).use();
}
else {
((CoinTest) fixA.getUserData()).use();
}
The player class's fixturedef maskbits include coin, and coin class's maskbits include the player (everything is done the same way as with ground, platforms, ladders etc., and the problem only exists here).
I hope I explained this well enough, this is my first question here.
fixA.getUserData()
may return null and throw when you try to invokeuse()
at it. - pafau k.Body
and not theFixture
? - bornander