Hello forum, recently I began to use a Tiled map for my game. I was thinking about using a more traditional AABB collision method but then found out I can get tile ID's and so I would imagine I could figure out collision that way. I was trolling through past posts about Tiled and collision detection and came upon this:
Moving on. This is you would get the ID of a Tile with libgdx:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
| private int computeCollisionLayerIndex(TiledMap map) { for (int i = 0; i < map.getLayers().getCount(); i++) { if (map.getLayers().get(i).getName().equalsIgnoreCase("collision")) { return i; } } return -1; }
public void whatevername(TiledMap map) { int collisionLayerIndex = computeCollisionLayerIndex(map); if (collisionLayerIndex != -1) { MapLayer layer = map.getLayers().get(collisionLayerIndex if (layer instanceof TiledMapTileLayer) { getCollisionTilesFrom((TiledMapTileLayer) layer); } else throw some kind of error } else throw some kind of error }
public void getCollisionTilesFrom(TiledMapTileLayer layer) { for (int x = 0; x < layer.getWidth(); x++) { for (int y = 0; y < layer.getHeight(); y++) { TiledMapTileLayer.Cell cell = layer.getCell(x, y); if (cell == null) continue; if (cell.getTile() == null) continue; System.out.println(cell.getTile().getID()); } } } |
With this code in particular
1
| TiledMapTileLayer.Cell cell = layer.getCell(x, y); |
You can get the ID from a specific cell. Now for the questions:
1. What would the cell ID turn up as ? A number or some string - how would this be relevant to what is exactly placed?
2. After I figure out when my player is next to a certain tile, how could i prevent the player from moving onto that tile? Would there be a simple way to determine if the tile is to the left of the character, and making a variable like isAbleToMoveLeft set to false if its near a tile where it can not move left.Maybe something like this?
1 2 3
| if(collisionTile.x < player.x){ isAbleToMoveLeft = false; } |
3. Final question is this: I have items drawn in 4 layers in Tiled. Is this something that will effect the way collision detection works? In the method written by matheus23 the
getCollisionTilesFrom method requires a layer. So I am curious if 4 layers will create problems.
Thanks for the help!
