Libgdx Collision Detection with TiledMap

时光总嘲笑我的痴心妄想 提交于 2019-12-04 12:14:07

问题


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.


回答1:


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. Find the collision layer in your map
  2. Extract all objects from this layer
  3. 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:

  • Java Tiled Map Game (LibGDX) | Episode 4 - collision detection
  • Java Tiled Map Game (LibGDX) | Episode 4 update - better collision detection implementation
  • Android Game Development with libgdx – Collision Detection, Part 4
  • SuperKoalio example game with TiledMaps and collision


来源:https://stackoverflow.com/questions/20063281/libgdx-collision-detection-with-tiledmap

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!