One of the challenges in using tile maps is that we have at least two different coordinate positions that can be used to refer to a position on the map: pixels on the tilemap, and the tile coordinates. The tile coordinates relate to each individual tile, so the top left tile is (0,0) and the bottom right is (49,49) for our 50 by 50 map. What we need are some helper methods to easily convert between the two.
-(CGPoint)tileCoordForPos:(CGPoint)pos { // Convert map posiiton to tile coordinate NSInteger x = pos.x / tw; NSInteger y = ((tmh * th) - pos.y) / th; return ccp(x,y); }
Here we are finally making use of the shorthand variables we saw in the init
method. As a refresher, the variables are as follows:
tmw
= tilemap widthtmh
= tilemap heighttw
= tile widthth
= tile height
So the x
value is the position divided by the tile width. For the y
value, the calculation is a little longer, because the origin point of the tile...