Libgdx collision detection with tiledmap
I'm trying to implement a collision detection system by tiling maps I have a 2D Pokemon style game with a tiled map Specifically, my tile map There is a "collision" layer in the TMX file, and I want to interact with the player and other entities My problem is how to connect the player sprite (extended sprite class) to the "collision" layer of the tile map and cause a collision between the two Any suggestions are appreciated
Solution
First, your player should probably not extend sprite because your player is usually more than just an elf It may include several sprites or even animation Keep Elves as player's property
The problem itself has been solved many times You usually need the following steps:
>Find collision layers in the map > extract all objects from this layer > check each object for collisions
In the code, this might look 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 } }
More links 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