Game Development Reference
In-Depth Information
the few exceptions where you'll have to deal with conversion between pixel and point
coordinates to ensure correct behavior on both standard- and Retina-resolution devices.
If the touch were at the 340 x position, the calculation would reveal the following:
340 / 32 = 10.625
That can't be right, though. You're looking for a tile's x coordinate, which is never a
fractional number! The reason is, of course, that the touch was somewhere inside the
tile we're looking for (that is, inside a 32×32 square area). The simple trick of casting
the result to an int value will get rid of the fractional part and assign this to pos.x :
pos.x = (int)10.625 // pos.x == 10
Casting to an int will remove the fractional part. You can safely get rid of the frac-
tional part because it's simply not relevant—actually it's harmful. If you didn't cast
away the fractional part but used the noninteger coordinate—in this example,
10.625—to try to retrieve the tile at a tile coordinate 10.625, you'd receive a runtime
error because there is only a tile at x coordinates 10 and 11, not at 10.625.
You use a slightly more complicated calculation to get the tile's y coordinate:
float pointHeight = tileMap.tileSize.height / CC_CONTENT_SCALE_FACTOR();
pos.y = (int)((tileMap.mapSize.height * pointHeight - pos.y) / pointHeight);
Note that the parentheses are important to make sure the division is done last. In actual
numbers, this calculation may be easier to understand. As shown in Figure 10-5 , the
tileMap.mapSize is 30 × 20 tiles, and as I mentioned earlier,
tileMap.tileSize is 32 × 32 pixels. The calculation then looks like this:
pos.y = (int)((20 * 32 - 260) / 32)
Multiplying tileMap.mapSize.height with pointHeight returns the full
height of the tilemap in points. This is necessary because the tilemap starts counting y
coordinates from top to bottom, whereas screen y coordinates count from bottom to
top. By calculating the bottommost y coordinate of the tilemap and subtracting the cur-
rent y position 260 from that, you get the correct y position of the touch into the
tilemap, in points. And because it's a point coordinate, which can have a fractional