I am trying to convert the pixel co-ordinates of my character sprite to grid co-ordinates so that I can check whether the user is touching a certain tile on the map.
Here is my code:
CGPoint mappos = [tileMapNode convertToNodeSpace:position];
mappos.x = (int) mappos.x / tileWidth;
mappos.y = (int) mappos.y / tileWidth;
CCTMXLayer *metaLayer = [tileMapNode layerNamed:@"Meta"];
CCSprite *metaTile = [metaLayer tileAt:ccp(mappos.x, mappos.y)];
if (metaTile)
{
NSLog(@"HIT!");
}
For some reason the character position just doesn't line up properly with the grid co-ordinates. Why is that?
I used this and worked in all case.
#define IS_IPAD (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
#define TILE_SIZE ( IS_IPAD ? 64 : 32 )
#define TILE_IN_ROW ( IS_IPAD ? 19 : 19 )
#define TILE_IN_COL ( IS_IPAD ? 32 : 30 )
#define TILE_MAP_HEIGHT (TILE_IN_COL*TILE_SIZE)
#define PP_TILE_META_LAYER @"Meta"
#define PP_TILE_MAP_BG_LAYER @"Background"
- (CGPoint)getTileCoordForPosition:(CGPoint)position
{
int maxTileCol = self.mapSize.height;
int x = ( (position.x-self.position.x)/TILE_SIZE);
int y = maxTileCol - ( ((position.y)-self.position.y)/TILE_SIZE);
if( x >= TILE_IN_ROW)
x = TILE_IN_ROW - 1;
if( y >= TILE_IN_COL)
y = TILE_IN_COL - 1;
return ccp(x, y);
}
mBgLayer = [self layerNamed:PP_TILE_MAP_BG_LAYER];
CGPoint point = [self getTileCoordForPosition:position];
CCSprite *sprite = [mBgLayer tileAt:point];