Game Development Stack Exchange is a question and answer site for professional and independent game developers. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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).

share|improve this question
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
up vote 4 down vote accepted

Ok this code is based on all tiles being shown on the screen.

x = (int) (posX / tileWidth)
y = (int) (posY / tileHeight)

If you don't have all tiles on screen then you would offset the x,y from above by the lowest x,y cell you are displaying.

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.