Game Development Reference
In-Depth Information
Locating Touched Tiles
I mentioned the tilePosFromLocation method earlier, and I'll repeat the two rel-
evant lines from the ccTouchesBegan code here before getting to the implementa-
tion of locationFromTouch and tilePosFromLocation :
// Get the position in tile coordinates from the touch location
CGPoint touchLocation = [self locationFromTouch:touches.anyObject];
CGPoint tilePos = [self tilePosFromLocation:touchLocation tileMap:tileMap];
First, the position of the touch is mapped to screen coordinates. I've done this before,
but because you'll be needing this code a lot, I've provided it in Listing 10-2 for your
reference.
Listing 10-2 . Determining the Position of a Touch
-(CGPoint) locationFromTouch:(UITouch*)touch
{
CGPoint touchLocation = [touch locationInView:touch.view];
return [[CCDirector sharedDirector] convertToGL:touchLocation];
}
With the touch location converted to screen coordinates, the tilePosFromLoca-
tion method is called. It gets both the touch location and a pointer to the tileMap
as parameters. The method in Listing 10-3 contains a bit of math, which I'll explain in
Listing 10-3 . Converting Location to Tile Coordinates
-(CGPoint) tilePosFromLocation:(CGPoint)location tileMap:(CCTMXTiledMap*)tileMap
{
// Tilemap position must be offset, in case the tilemap is scrolling.
CGPoint pos = ccpSub(location, tileMap.position);
// scaling tileSize to Retina display size
float pointWidth = tileMap.tileSize.width / CC_CONTENT_SCALE_FACTOR();
float pointHeight = tileMap.tileSize.height / CC_CONTENT_SCALE_FACTOR();
// Cast to int makes sure that result is in whole numbers