[英]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添加到“燈具和實體”中,如果發生碰撞,可以讀取它們。
創建檢查點的實體時,將用戶數據添加到夾具和主體中:
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
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.