提问者:小点点

Libgdx和Box2d检测两个特定物体的碰撞


我有两个身体,都是动态的,其中一个我已经关闭了重力,只有当它被我的另一个身体击中时才想打开它。我知道我可以设置自己的联系人侦听器,但我想指定一个动作,只有当两个特定的身体接触时。

有人有指导吗?


共1个答案

匿名用户

你可以设置主体的userdata并这样使用它

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);

}

希望这能解决你的问题