Libgdx Collision Detection with TiledMap

I am struggling with the implementation of a collision detection system through tiledmap. I have a 2d "Pokemon game" that displays a tile map. In particular, I have a “collision” layer in my .tmx file with a tile file that I want to interact with the player and other objects. My question is how to associate a sprite (extension of the Sprite class) with a “collision” layer with tiles and cause a collision between them. Any advice is appreciated.

+6
source share
1 answer

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

The question itself has already been considered several times. Usually you need the following steps:

  • Locate the collision layer on the map.
  • Extract all objects from this layer
  • Check each of these objects for a collision.

In code, it might look something 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 that may interest you:

+12
source

Source: https://habr.com/ru/post/958359/


All Articles