I was curious as to how you would go about converting from pixel to tile precision on a tile map. For example, let's say my map is comprised of 8x6 tiles, each of which are 50x50 pixels in size. If I could only get the current coordinates of my mouse in pixels, how would I go about finding which tile those pixels are contained in programmatically?
1 Answer
\$\begingroup\$
\$\endgroup\$
2
It's quite simple. Just divide your position with tile dimensions. Like this.
tileX = positionX / tileWidth
tileY = positionY / tileHeight
this will give you x and y tile, where your position is. This assumes that your top left tile is at 0,0 coordinates.
So, in your case, lets say coordinates are x:256,y:172
tileX = x / 50
tileY = y / 50
This would result
tileX = 5
tileY = 3
-
\$\begingroup\$ Erm... wow. Yah that's certainly a lot simpler than I expected. \$\endgroup\$ Commented Jul 9, 2014 at 9:26
-
\$\begingroup\$ @r0llingthund3r you'll find a lot of solutions are simpler than you think. It's the perks of logic in programming. You look like you're pretty new so come into the Chat and join us for a while. You might learn even more! \$\endgroup\$ Commented Jul 9, 2014 at 9:52