Game Development Reference
In-Depth Information
pos.x = (int)(pos.x / pointWidth);
pos.y = (int)((tileMap.mapSize.height * pointHeight - pos.y) / pointHeight);
// Ensure coordinates are always within tilemap bounds.
pos.x = fmaxf(0, fminf(tileMap.mapSize.width - 1, pos.x));
pos.y = fmaxf(0, fminf(tileMap.mapSize.height - 1, pos.y));
return pos;
Still with me? If you've worked with tilemaps before, this bit of code should be famili-
ar, but if not, you may be at a loss. I'll explain. The first thing this method does is sub-
tract the current tileMap.position from the touch location. The upcoming
changes to the Tilemap project will add tilemap scrolling, so the tilemap's position will
most likely not be at 0,0, and that needs to be factored in by subtracting the tilemap's
position from the location.
To make the viewpoint scroll farther up (north) and to the right (east), you actually
have to change its position by negative amounts. That's because the tilemap starts at
position 0,0, which positions the map's bottom left-hand corner at the very bottom left
of the screen. The tilemap's 0,0 point coincides with the screen's 0,0 point initially. If
you were to move the tilemap to position 100,100, it would seem as if the viewpoint
were moving toward the left and down. The common mistake is to assume that you're
moving the viewpoint, which you are not. The tilemap layer is what's moving, and to
scroll farther toward the center of the tilemap, you have to offset the tilemap by negat-
ive values.
The rest is simple math: to get the proper offset from the tilemap (whose position you
know is always negative), you have to subtract the touch location and
tileMap.position . The concrete numbers reveal that subtracting a negative num-
ber is actually an addition:
location(240, 160) - tileMap.position(−100, -100) = pos(340, 260)
With the tilemap layer moved −100,-100 pixels away from the screen's 0,0 point, and
the touch being at 240,160 pixels on the screen, the total offset of the touch location
from the tilemap's position is 340,260 pixels away from the current
tileMap.position .
Search Nedrilad ::

Custom Search