Libgdx and Box2d Detect Collision of two specific bodies

喜欢而已 提交于 2019-11-29 16:32:21

U can set the userdata of the body and use it like that

public class GameColiision implements ContactListener

 {

public GameColiision()
{


}

@Override
public void beginContact(Contact contact) {
    // TODO Auto-generated method stub
    Body a=contact.getFixtureA().getBody();
    Body b=contact.getFixtureB().getBody();
    a.getUserData();
    if(a.getUserData() instanceof Obstacle&&b.getUserData() instanceof Car)
    {

    }
}

@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

}

}

public class Obstacle 
 {

public Body rectangleBody;
public Body triangleBody;
World world;
public static final float WIDTH=10/40f; 
public static final float HEIGHT=10/40f; 


public Obstacle(World world,float x,float y) 
{
    this.world=world;
    initRectangle(x,y);
}


private void initRectangle(float x, float y) 
{
    BodyDef  bodyDef=new BodyDef();
    FixtureDef fixtureDef=new FixtureDef();

    bodyDef.type=BodyType.DynamicBody;
    rectangleBody=world.createBody(bodyDef);

    PolygonShape  polygonShape=new PolygonShape();

    polygonShape.setAsBox(WIDTH,HEIGHT);
    fixtureDef.shape=polygonShape;

    fixtureDef.friction=1f;
    fixtureDef.density = 1f;

    rectangleBody.createFixture(fixtureDef);
    rectangleBody.setTransform(x, y, 0) ;   
    rectangleBody.setAngularDamping(0);

    rectangleBody.setUserData(this);

}

Hope this solves your problem

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!