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
Libgdx Collision Detection with TiledMap
提问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 Player
should 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:
这个问题本身已经被多次提及。您通常需要以下步骤:
- Find the collision layer in your map
- Extract all objects from this layer
- Check each of those objects for a collision
- 在地图中找到碰撞层
- 从此层中提取所有对象
- 检查每个对象是否发生碰撞
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:
您可能感兴趣的更多链接: