【发布时间】:2018-04-25 10:45:37
【问题描述】:
我正在 LibGDX 中开发一款游戏,并使用 Tiled 设置了一张地图。我为特定层中的对象添加了一个自定义 String 属性,以获取更多信息,它代表什么对象。
我设置了一个 ContactListener,它调用地图对象抽象类中的一个方法。监听器看起来像这样:
@Override
public void beginContact(Contact contact) {
Fixture fixtureA = contact.getFixtureA();
Fixture fixtureB = contact.getFixtureB();
if (fixtureA.getUserData() == "player" || fixtureB.getUserData() == "player") {
// Get either fixture A or B, depending on which of them is the player fixture
Fixture player = fixtureA.getUserData() == "player" ? fixtureA : fixtureB;
// Get the colliding object, depending on which of them is the player fixture
Fixture collidedObject = player == fixtureA ? fixtureB : fixtureA;
// Determine what kind of object the player collided with and trigger the respectable method
if (collidedObject.getUserData() instanceof InteractiveMapTileObject) {
((InteractiveMapTileObject) collidedObject.getUserData()).onPlayerBeginContact();
} else if (collidedObject.getUserData() instanceof Enemy) {
((Enemy) collidedObject.getUserData()).onPlayerBeginContact();
}
}
}
当玩家点击 InteractiveMapTileObject 实例的对象时,会调用 onPlayerBeginContact() 方法,如下所示:
@Override
public void onPlayerBeginContact() {
MapObjects objects = playScreen.getMap().getLayers().get("weapon").getObjects();
for (MapObject object : objects) {
if (object.getProperties().containsKey("weapon_name")) {
String weaponName = object.getProperties().get("weapon_name", String.class);
Gdx.app.log("Picked up weapon", weaponName);
}
}
}
在这里,我正在获取地图中“武器”图层的对象,然后对其进行迭代以找到正确的属性及其值。这工作正常。
现在的问题是,我显然在图层中有多个对象,因此有多个 MapObjects。我需要一种方法来识别玩家碰撞的对象,然后获取它的属性。
是否可以使用 ContactListener 做到这一点,还是我需要实现其他东西?我已经搜索了很多帖子,但没有走运。
【问题讨论】:
标签: java libgdx collision-detection tiled