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

  • \$\begingroup\$ 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]; \$\endgroup\$ Feb 1 '13 at 17:41
  • 2
    \$\begingroup\$ 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]; \$\endgroup\$ Feb 1 '13 at 17:44
  • 3
    \$\begingroup\$ 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. \$\endgroup\$
    – House
    Feb 1 '13 at 17:47

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.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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