Reputation: 119
public class Contact implements ContactListener {
@Override
public void beginContact(Contact contact) {
Fixture fa = contact.getFixtureA();
Fixture fb = contact.getFixtureB();
if (fa.getFilterData().categoryBits==16){
((Gamescreen)fa.getUserData()).starttouch(fa,fb);
}
@Override
public void endContact(Contact contact) {
Fixture fa = contact.getFixtureA();
Fixture fb = contact.getFixtureB();
if (fa.getFilterData().categoryBits==16)
{
((Gamescreen)fa.getUserData()).endtouch();
}
this code works fine when there is just one object to touch but some time i need to make like tow object beside of each others. like when the player walk on 2 objects (without jumping) beside each others the second method (endcontact) called but the first method (begincontact) does not get call again.
Upvotes: 1
Views: 131
Reputation: 1301
Are you sure that beginContact()
is not called? Try printing something out. Im pretty sure that it's more like this: your object collides with object A and B, and when one of them is ending contact, your object gets to state like there is no object colliding to it.
To prevent that you should count collisions.
You can add 2 functions to your Gamescreen: incCollision()
and decCollision()
.
Call them respectively in beginContact()
and endContact()
.
Also it might be risky assume that fa
will always be instance of Gamescreen
.
@Override
public void beginContact(Contact contact){
Fixture fa = contact.getFixtureA();
Fixture fb = contact.getFixtureB();
if(fa == null || fb == null) return;
handleGamescreenContact(fa, fb, true);
}
@Override
public void endContact(Contact contact){
Fixture fa = contact.getFixtureA();
Fixture fb = contact.getFixtureB();
if(fa == null || fb == null) return;
handleGamescreenContact(fa, fb, false);
}
private void handleGamescreenContact(Fixture fixA, Fixture fixB, boolean inc){
Fixture gamescreen = fixA.getUserData() instanceof Gamescreen ? fixA : fixB;
Fixture something = fixA.getUserData() instanceof Gamescreen ? fixB : fixA;
if(gamescreen.getFilterData().categoryBits==16){
if(inc)
((Gamescreen)gamescreen.getUserData()).incCollision();
else
((Gamescreen)gamescreen.getUserData()).decCollision();
}
}
And how inc/dec functions will look:
public void incCollision(Fixture fa, Fixture fb){
collisionCounter++;
startTouch(fa, fb);
}
public void decCollision(){
collisionCounter--;
if(collisionCounter <= 0)
endTouch();
}
Upvotes: 1