2012-07-15 34 views
1

我對使用iPhone的Cocos2d相當陌生,而且觸摸位置有問題。目前,我只是試圖在屏幕上觸摸並移動一個精靈,當圖層不移動時以及當我翻譯圖層時(在我的情況下在X方向上改變self.position),這可以正常工作,但是當我縮放我的圖層(例如:self.scale = .5)觸摸不再移動精靈。我做了很多論壇搜索/谷歌搜索,我認爲我的問題與我的座標變換(節點空間/世界空間等)有關,但我不是100%確定的。我注意到當我縮放時,如果我點擊精靈所在的位置而沒有縮放,那麼我可以移動精靈。這讓我相信我的轉換沒有考慮到這個尺度。cocos2d - 刻度後不再正常工作

這裏是座標變換我目前使用得到的觸摸位置的代碼:

- (void)ccTouchesBegan:(NSSet *)touches withEvent:(UIEvent *)event 
{ 
    UITouch *myTouch = [touches anyObject]; 
    CGPoint location = [myTouch locationInView:[myTouch view]]; 
    location = [self convertToNodeSpace:location]; 
    location = [[CCDirector sharedDirector] convertToGL:location]; 
} 

這裏是如果位置(同一位置如上述變量)正在觸摸精靈被檢查的代碼,雖然我覺得這個代碼是正確的,誰知道!

for (CCSprite *sprite in movableSprites) { 
    if (CGRectContainsPoint(sprite.boundingBox, touchLocation)) { 
     NSLog(@"Woohoo, you touched a sprite!"); 
     break; 
    } 
} 

讓我知道如果您需要了解更多信息,並感謝您的閱讀!

+0

嗯,我想你需要使用convertToWorldSpace那裏,因爲你想要的位置沒有轉換到圖層的空間(這是縮放)。可能是錯誤的。 – LearnCocos2D 2012-07-15 22:43:51

回答

1

我想你應該隨着規模

for (CCSprite *sprite in movableSprites) { 
    if (CGRectContainsPoint(sprite.boundingBox*sprite.scale, touchLocation)) { 
     //touch sprite action 
    } 
} 

一倍邊框有關轉換點,如果我需要一個絕對屏幕點我總是用:

convertToWorldSpace:CGPointZero. 

我不是真的當然,爲什麼你需要在你的觸摸位置上使用它,當我需要忽略它們在父節點中的位置時,我通常會在精靈上執行此操作。

其他然後是,如果你的遊戲是不是真正的多點觸控遊戲你更好地使用ccTouchBegan而不是ccTouchesBegan。

0

使用此功能來獲得精靈矩形。

-(CGRect)getSpriteRect:(CCNode *)inSprite 
{ 
    CGRect sprRect = CGRectMake(
           inSprite.position.x - inSprite.contentSize.width*inSprite.anchorPoint.x, 
           inSprite.position.y - inSprite.contentSize.height*inSprite.anchorPoint.y, 
           inSprite.contentSize.width, 
           inSprite.contentSize.height 
           ); 

    return sprRect; 
} 



- (void)ccTouchesBegan:(NSSet *)touches withEvent:(UIEvent *)event 
{ 
    UITouch *myTouch = [touches anyObject]; 
    CGPoint location = [myTouch locationInView:[myTouch view]]; 
    location = [[CCDirector sharedDirector] convertToGL:location]; 

    for (CCSprite *sprite in movableSprites) 
    { 
     CGRect rect = [self getSpriteRect:sprite]; 
     if (CGRectContainsPoint(rect, location)) 
     { 
      NSLog(@"Woohoo, you touched a sprite!"); 
      break; 
     } 
    } 
}