Collision Detection with a tiled map (.tmx)

Hey!
I am trying to get the X and Y cordinates of every tile in my tiled map. I cant find out how i should do this. Or is there a better way to check for collision with the tiles?

You must transform screen coordinates to tile coordinates by dividing the x by the tile width and the y by the tile height.
I think this is the fastest method.

This is how I used to convert my mouse X/Y to tell me what tile I was hovered over when I used .tmx files, might help get you started.


	public int getTileX(){return (int)Math.floor(mapX()*-1+mouseX)/tileWidth;}
	public int getTileY(){return (int)Math.floor(mapY()*-1+mouseY)/tileHeight;}

also, here is a simple loop that would just loop through the entire map. Every step you can check a tile for a “blocked” property, or whatever it is you use to build your collision map:

EDIT: Note that you can remove the mapLayers part of your loop if all your blocking is only happening on one layer. In my old engine I had to potential for blocked objects on multiple layers, so I had to check those as well.


	for (int x = 0; x < mapWidth; x++) {
		for (int y = 0; y < mapHeight; y++) {
			for (int l = 0; l < mapLayers; l++) {
				//x*tileWidth, y*tileHeight == tile the loop is currently on.
				do.stuff(here);
			}
		}
	}

Why you need to check the full map if you know the portion of the map where your sprite is located? This is slow.

This is going under the assumption he wants to check the entire map, because he said:

[quote]I am trying to get the X and Y cordinates of every tile in my tiled map.
[/quote]
There are cases where you want to check all the tiles, I actually used this in one of my games to build/load the collision rectangle objects into an ArrayList in advance. When it came to calculating rectangles/collisions, that’s when I only calculated around the area the player (or other entities) were in.

I tried this: http://pastebin.com/0ZSUQHBc
When I jump on a block or walk to a side of the block it stops the player moving. but not at the same position some times there is a 1 px gab or -2 or + 2 or whatever random amount of pixels inbetween the player and the block. Why is this? (i dont know if the block’s position matters)

This is probably because you moved more units in a single frame than the distance to the wall. Say you have a velocity of 5, but the distance to the wall is only 23 units. After 4 frames you will have covered a distance of 20 units and there are 3 units left until you reach the wall. In the next frame it will move 5 units, thus moving 2 pixels into the wall. In the frame after this it will realize it’s not allowed to move anymore.
Try solving this with implementing collision casting. Your object should look forward when checking for collision. If the velocity is greater than the distance, it should only move the distance and not the velocity.