2
\$\begingroup\$

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?

\$\endgroup\$

1 Answer 1

2
\$\begingroup\$

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
\$\endgroup\$
2
  • \$\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

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .