Java 使用 TiledMap 进行 Libgdx 碰撞检测

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20063281/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 22:46:46  来源:igfitidea点击:

Libgdx Collision Detection with TiledMap

javalibgdxcollision-detection

提问by bhafenri

I'm struggling with implementing a collision detection system through the tiledmap. I have a 2d "pokemon style" game that has a tiled map rendered. Specifically, I have a 'collision' layer in my tiled map .tmx file that I want to interact with the player and other entities. My question is how do I connect the player sprite (extends Sprite class) to the 'collision' layer of the tiledmap and cause collision between the two. Any advice is appreciated.

我正在努力通过平铺地图实现碰撞检测系统。我有一个 2d“口袋妖怪风格”游戏,它渲染了一个平铺地图。具体来说,我的平铺地图 .tmx 文件中有一个“碰撞”层,我想与玩家和其他实体进行交互。我的问题是如何将玩家精灵(扩展精灵类)连接到平铺地图的“碰撞”层并导致两者之间发生碰撞。任何建议表示赞赏。

采纳答案by noone

First of all your Playershould probably not extend Sprite, because your player is usually much more than a Sprite. It probably consists of several sprites or even Animations. Keep a sprite as a property of the player.

首先,您Player可能不应该这样做extend Sprite,因为您的播放器通常不止一个Sprite. 它可能由几个精灵甚至Animations. 保持精灵作为玩家的属性。

The question itself has already been adressed several times. You usually need the following steps:

这个问题本身已经被多次提及。您通常需要以下步骤:

  1. Find the collision layer in your map
  2. Extract all objects from this layer
  3. Check each of those objects for a collision
  1. 在地图中找到碰撞层
  2. 从此层中提取所有对象
  3. 检查每个对象是否发生碰撞

In code this might look a bit like this:

在代码中,这可能看起来有点像这样:

int objectLayerId = 5;
TiledMapTileLayer collisionObjectLayer = (TiledMapTileLayer)map.getLayers().get(objectLayerId);
MapObjects objects = collisionObjectLayer.getObjects();

// there are several other types, Rectangle is probably the most common one
for (RectangleMapObject rectangleObject : objects.getByType(RectangleMapObject.class)) {

    Rectangle rectangle = rectangleObject.getRectangle();
    if (Intersector.overlaps(rectangle, player.getRectangle()) {
        // collision happened
    }
}

Some more links which you might be interested in:

您可能感兴趣的更多链接: