I used the tile tutorial from http://www.raywenderlich.com. I set up a tile map in a landscape view and used the code from the tutorial to detect touch, like this:
CGPoint touchLocation = [touch locationInView: [touch view]];
touchLocation = [[CCDirector sharedDirector] convertToGL: touchLocation];
touchLocation = [self convertToNodeSpace:touchLocation];
And use this bit to figure which tile it is on:
CGPoint touchTilePos = [self tileCoordForPosition:touchLocation];
int tileIndex = [self tileIndexForTileCoord:(touchTilePos)];
CCSprite *touchTile = [self.background tileAt:touchTilePos];
self.player.position = [touchTile.parent convertToWorldSpace:touchTile.position];
Problem is that it’s a bit off. Touch close to the left side is fairly close, but touch close to the right side is detected way off to the left. Seems like some sort of scaling issue, but the only scaling in my code is the player sprite.
Any ideas? Suggestions?
Any halp is greatly appreciated!
EDIT: here is the two methods referenced in the code:
- (CGPoint) tileCoordForPosition:(CGPoint)position
{
int x = position.x / _tileMap.tileSize.width;
int y = ((_tileMap.mapSize.height * _tileMap.tileSize.height) - position.y) / _tileMap.tileSize.height;
return ccp(x, y);
}
- (int) tileIndexForTileCoord:(CGPoint)aTileCoord
{
return aTileCoord.y*(self.tileMap.mapSize.width) + aTileCoord.x;
}
UPDATE:
I simplified the code:
CGPoint touchLocation = [touch locationInView: [touch view]];
touchLocation = [[CCDirector sharedDirector] convertToGL: touchLocation];
touchLocation = [self.background convertToNodeSpace:touchLocation];
int x = touchLocation.x / _tileMap.tileSize.width;
int y = ((_tileMap.mapSize.height * _tileMap.tileSize.height) - touchLocation.y) / _tileMap.tileSize.height;
CGPoint touchTilePos = ccp(x,y);
Also, i noticed that right off the start, touchLocation is off to the left, i don’t think this code works correctly for my case (iPad/landscape):
CGPoint touchLocation = [touch locationInView: [touch view]];
I made a fatal mistake! I am using HEX tiles, and they overlap a bit (about 1/4). I have to account for that! And that’s why the effect gets worse as i tap further to the right,
Here is the code to fix it:
Cheers!