2012-04-24 106 views
1

我使用了www.raywenderlich.com的磁贴教程。我成立了一个横向视图瓦片地图和使用的代码从教程来检测触摸,就像这样:CCTMXTiledMap触摸检测有点关闭

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]; 

问题在于它有点偏离。触摸靠近左侧的位置非常靠近,但触摸靠近右侧的位置会被检测到向左移动。看起来像某种缩放问题,但我的代码中唯一的缩放比例是玩家精灵。

任何想法?建议? 任何halp非常感谢!

编辑:这是在代码中引用的方法有两种:

- (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]]; 

回答

2

我犯了一个致命的错误!我使用HEX瓷砖,它们重叠了一些(约1/4)。我必须解释它!这就是为什么效果会变得更糟,因为我进一步挖掘到右侧, 下面是代码来解决它:

int x = (touchLocation.x - tileSize.width/8)/(_tileMap.tileSize.width * (3.0/4.0)) ; 
    int y = 0; 
    if(x % 2 == 0) 
    { 
     // even 
     y = ((_tileMap.mapSize.height * tileSize.height) - touchLocation.y)/tileSize.height; 
    } 
    else 
    { 
     // odd 
     y = ((_tileMap.mapSize.height * tileSize.height) - (touchLocation.y + tileSize.height/2))/tileSize.height; 
    } 
    CGPoint touchTilePos = ccp(x,y); 

干杯!

+0

upvoted回来并回答你自己的问题!对不起,我以前没有回复〜 – MechEthan 2012-04-30 17:04:27

0

教程代码看起来应该可以正常工作。我使用数学上与一致/正确结果相同的代码。

我唯一的建议是双倍确定self这一行中的对象: touchLocation = [self convertToNodeSpace:touchLocation];是TMXMap的实际直接父节点。

在我的代码中,CCLayer不是直接父,所以我最终明确标注我的地图的父节点,所以我可以抓住它是这样的:

CCNode *parentNode = [self getChildByTag:kTagParentNode]; 
CGPoint worldPt = [parentNode convertToNodeSpace:touchLocation]; 
+0

嗨,谢谢你的帮助!我怎么能检查是否TMXMap的实际父节点?有没有办法显示一些调试信息? – SpaceBear 2012-04-26 02:23:54

+0

TMXMap的父节点只是您调用'[... addChild:TMXMap ...]'的任一节点。看起来我是带领你走错了方向,对不起! – MechEthan 2012-04-30 17:05:18