Java / LibGDX:在box2D冲突中获取自定义对象属性

时间:2019-05-20 06:25:16

标签: java libgdx box2d

我正在游戏中设置检查点,并希望玩家每次重生时都能获得原本应该的颜色。否则,玩家会立即死亡。

我已经在我的联系人监听器中尝试了这段代码(检查夹具a(玩家)和夹具b(检查点)之间的联系):

MapObjects objects = play.getTileMap().getLayers().get("checkpoints").getObjects();

for (MapObject object : objects) {
    if (object.getProperties().containsKey("Color")) {
        int color = object.getProperties().get("Color", Integer.class);
        Gdx.app.log("Respawn color", Integer.toString(color));
        game.setRespawnColor(color); 
    }
}

但是,此代码不是从与玩家碰撞的检查点获得“颜色”属性,而是从找到的最后一个检查点获得

一种解决方法是,例如,为每种颜色(red_checkpoint)添加一个检查点图层,但这会添加感觉到很多不必要的代码。

谢谢!

1 个答案:

答案 0 :(得分:2)

您可以将UserData添加到灯具和实体中,如果它们发生冲突,则可以读取。

创建检查点的实体时,将用户数据添加到灯具和主体中:

Body body = world.createBody(bodyDef);
body.setUserData(Checkpoint.COLOR_RED); //Set the Color of the Checkpoint as Body UserData

FixtureDef fixtureDef = new FixtureDef();
Fixture fixture = body.createFixture(fixtureDef);
fixture.setUserData(Type.CHECKPOINT); //Set the Type of the fixture to detect if it a Checkpoint

检查点枚举看起来像这样:

public enum Checkpoint {
    COLOR_RED(1),
    COLOR_GREEN(2);

    public final color;
    Checkpoint(int colorValue){
        color = colorValue;
    }
}

然后在您的碰撞侦听器中,可以获取以下UserData:

Fixture fixA = contact.getFixtureA();
Fixture fixB = contact.getFixtureB();

Checkpoint collidedCheckpoint = null;
if(fixA.getUserData == Type.CHECKPOINT){ //Check if fixA is a Checkpoint
    collidedCheckpoint = ((Checkpoint)fixA.getBody().getUserData());
} else if(fixB.getUserData == Type.CHECKPOINT){ //Check if fixB is a Checkpoint
    collidedCheckpoint = ((Checkpoint)fixB.getBody().getUserData());
}
if(collidedCheckpoint != null){
    //Get the color of the Checkpoint by saving a int in the enum or something else
    int color = collidedCheckpoint.color; // 1
} else {
    //Not with a Checkpoint collided
}