# In a regular grid, how can I tell which tile a position is in?

I have a position on the screen, how do I calculate which grid tile that position is inside?

I know the number of tiles in the grid, and the size of the screen (including how many tiles fit on it horizontally and vertically).

-
Assuming that your map is either a 2D array of tiles (or a flatend version of that) You should be able to do something like: Tile playerTile = map[player.x][player.y]; – Benjamin Danger Johnson Feb 1 '13 at 17:41
oh, and if your x,y position doesn't correspond to the tiles index you can obtain the index values by doing something like: int xIndex = (int)(player.x / Tile.Width); int yIndex = (int)(player.y / Tile.Height); Tile playerTile = map[xIndex][yIndex]; – Benjamin Danger Johnson Feb 1 '13 at 17:44
You shouldn't need to extrapolate the tile the main character is on by using the screen height and width. If you're just laying down tiles until you hit the edge of screen, you're going to run into a lot of issues when someone has a different resolution. I was making an answer, but really there's not enough information to make anything more than a guess. You'd have to share how you're displaying the tiles, how you're storing the tiles in memory and how your positions relate to tile positions. – Byte56 Feb 1 '13 at 17:47

``````x = (int) (posX / tileWidth)