If you consideryour grass tile's position in the tilemap rows/columns as "world coordinates" then you can use a simple formula to convert x and y values to tilemap rows and columns:
Tile_Column = X / Tile_Size
Tile_Row = Y / Tile_Size
Note that the division operations should be using integers to automatically round the answer down for you. If you're using real value types you need to use math.floor().
For screen to world coordinates, you first have to define where the screen is <Gx,Gy>
then its pixel position in the game world will be:
View_X: The X position of the screen's top-left corner in world coordinates.
View_Y: The Y position of the screen's top-right corner in world coordinates.
tile_worldX = Gx * Tile_Size
tile_worldY = Gy * Tile_Size
Then you can convert onsubtract the position of the screen's top-screenleft corner from these coordinates to world coordinates (i.e: for a mouse click) with the following formulaget their on-screen pixel position:
World_X = View_X + Screen_X
World_Y = View_Y + Screen_Y
tile_screenX = tile_worldX - view_x
tile_screenY = tile_worldY - view_y
FinallyThis assumes that the screen's top-left corner is 0, you can take0 in your viewport. Sometimes game engines will move 0,0 to the World_X
and World_Y
values and put them intomiddle or bottom-left of the first formulaviewport so you may have to get which tilemap column/row the coordinate is insidecompensate for that difference.