使用 TiledMap 的 Libgdx 碰撞检测

时间:2023-03-01
本文介绍了使用 TiledMap 的 Libgdx 碰撞检测的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

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

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.

推荐答案

首先你的Player可能不应该extend Sprite,因为你的播放器通常比精灵.它可能由几个精灵甚至 Animations 组成.将精灵保留为玩家的属性.

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.

这个问题本身已经讨论过好几次了.您通常需要以下步骤:

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

  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:

  • Java 平铺地图游戏 (LibGDX) |第 4 集 - 碰撞检测
  • Java 平铺地图游戏 (LibGDX) |第 4 集更新 - 更好的碰撞检测实现
  • Android 游戏开发与 libgdx – 碰撞检测,第 4 部分
  • SuperKoalio 示例游戏使用 TiledMaps 和碰撞

这篇关于使用 TiledMap 的 Libgdx 碰撞检测的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

上一篇:为什么我在使用 Tiled 的 libgdx 游戏中出现线条? 下一篇:如何使用 libgdx 中的简单纹理绘制自定义形状?

相关文章