我使用了来自 www.raywenderlich.com 的瓷砖教程。我在横向视图中设置了一个平铺地图,并使用教程中的代码来检测触摸,如下所示:
CGPoint touchLocation = [touch locationInView: [touch view]];
touchLocation = [[CCDirector sharedDirector] convertToGL: touchLocation];
touchLocation = [self convertToNodeSpace:touchLocation];
并使用此位来确定它在哪个图块上:
CGPoint touchTilePos = [self tileCoordForPosition:touchLocation];
int tileIndex = [self tileIndexForTileCoord:(touchTilePos)];
CCSprite *touchTile = [self.background tileAt:touchTilePos];
self.player.position = [touchTile.parent convertToWorldSpace:touchTile.position];
问题是它有点偏离。靠近左侧的触摸相当接近,但靠近右侧的触摸被检测到离左侧很远。似乎是某种缩放问题,但我的代码中唯一的缩放是播放器精灵。
有任何想法吗?建议?非常感谢任何暂停!
编辑:这是代码中引用的两种方法:
- (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;
}
更新:我简化了代码:
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);
另外,我注意到一开始,touchLocation 就在左边,我认为这段代码不适用于我的情况(iPad/横向):
CGPoint touchLocation = [touch locationInView: [touch view]];