Java / LibGDX:在 box2D 碰撞上获取自定义对象属性

Java / LibGDX: Get custom object properties on box2D collision

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

我已经在我的接触侦听器中尝试了这段代码(检查夹具 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); 
    }
}

但是,此代码不会从玩家碰撞的检查点获取 属性 "Color",而是从它找到的最后一个检查点获取。

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

谢谢!

您可以将 UserData 添加到您的 Fixtures 和 Bodies 中,如果它们发生碰撞,您可以读取它们。

当您创建检查点的主体时,将用户数据添加到固定装置和主体:

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
}