Take the 2-minute tour ×
Game Development Stack Exchange is a question and answer site for professional and independent game developers. It's 100% free, no registration required.

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
2  
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
3  
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
add comment

1 Answer

up vote 3 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
add comment

Your Answer

 
discard

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.