I am developing a game in Libgdx and I am working on collision detection between two bodies in box 2D. I used "Contact Listener" to detect collision but nothing happens when the bodies collide.
This is my code
public Player(World world,float x,float y,float width)
{
this.width=width; //IMP
height=width*2;
BodyDef polygon=new BodyDef();
polygon.type=BodyType.DynamicBody;
polygon.position.set(x,y); //
polygon.fixedRotation=true;
PolygonShape poly =new PolygonShape();
poly.setAsBox(width/2,height/2); //
//fixture defn
polygon.position.set(5,4);
FixtureDef polyfixture=new FixtureDef();
polyfixture.shape=poly;
polyfixture.friction=0.8f; //
polyfixture.restitution=0.1f; //
polyfixture.density=3; //
//creating actual body
polybody=world.createBody(polygon);
polybody.createFixture(polyfixture);
polysprite=new Sprite(new Texture("img/car.jpg"));
polysprite.setSize(2, 3); //size of mario
polysprite.setOrigin(polysprite.getWidth()/2, polysprite.getHeight()/2);
polybody.setUserData(polysprite);
2nd body
BodyDef polygons=new BodyDef();
polygons.type=BodyType.DynamicBody;
PolygonShape polys=new PolygonShape();
polys.setAsBox(2,2);
FixtureDef polyxfixture=new FixtureDef();
polyxfixture.shape=polys;
polyxfixture.friction=0.8f;
polyxfixture.restitution=0.1f;
polyxfixture.density=3;
polybodys=world.createBody(polygons);
polybodys.createFixture(polyxfixture);
poly.dispose();
}
@Override
public void beginContact(Contact contact) {
// TODO Auto-generated method stub
Fixture fixtureA=contact.getFixtureA();
Fixture fixtureB=contact.getFixtureB();
if(fixtureA.getUserData() != null && fixtureA.getUserData().equals("polybody") &&
fixtureB.getUserData() !=null && fixtureB.getUserData().equals("polybodys")){
Gdx.app.log("Contact","1");
System.out.println("its colliding");
}
if(fixtureB.getUserData() !=null && fixtureB.getUserData().equals("polybody") &&
fixtureA.getUserData() !=null && fixtureA.getUserData().equals("polybodys"))
{
System.out.println("its colliding");
}
}
I have added world.setContactListener(player); also where "player" is the name of above class.
This is my code for detecting collision. When I run the code and test for collision between bodies nothing happens. I tested using "println" statement in console. I don't know which is wrong here. Please help. Thanks in advance !!