2009-08-24 139 views
0

嘿傢伙,我準備了很多關於這一點的問題,但我真的沒有得到正確的一個呢。問題與觸摸在cocos2D

所以..這就是問題所在..

這是我與cocos2d的第一個項目,因爲這很遺憾。

我有一個場景叫遊戲裏面,我有一個名爲電網一層,該網格內,有很多很多(LAYER太)。

我需要檢查,當你觸摸一個,我這樣做與Interface Builder之前,所以當我打電話touchesBegin我有一個視圖中的確切觸摸。但在cocos2D中,我明白你必須檢查對象的位置,而不是打中測試,然後對嗎?!

所以我touchesBegin是這樣的:

- (void)ccTouchesBegan:(NSSet*)touches withEvent:(UIEvent*)event 
{ 
    UITouch *touch = [touches anyObject]; 
    CGPoint location = [touch locationInView: [touch view]]; 
    //location = [[Director sharedDirector] convertCoordinate: location]; 

    for(int i = 0; i < [arrAllBlocks count]; i++) 
    { 
     for (int j = 0; j < [[arrAllBlocks objectAtIndex:i] count]; j++) 
     { 
      Block *tempBlock = [[arrAllBlocks objectAtIndex:i] objectAtIndex:j]; 
      CGRect mySurface = (CGRectMake(tempBlock.position.x, tempBlock.position.y, tempBlock.contentSize.width,tempBlock.contentSize.height)); 
      if(CGRectContainsPoint(mySurface, location)) 
      { 
       NSLog(@"Hit Positions %fl:%fl",location.x,location.y); 
       NSLog(@"Object Positions %fl:%fl",tempBlock.position.x,tempBlock.position.y); 
       NSLog(@"Object Color:%@ hited", tempBlock.strName); 
      } 
     } 

    } 
} 

的第一個問題是:這看起來顛倒!當我點擊第一行的這個塊之一時!我得到最後一行的塊!我真的不明白!對我來說這次擊球並不完美!而當我convertCoordinate這會變得更糟!

有人可以幫我嗎?對不起英語=/

+0

OpenGL從iPhone的其他部分使用倒置座標;我不知道Cocos2D如何處理這個問題,但是,這很煩人。 – 2009-08-26 12:53:48

回答

0

請記住,Cocos2D中的座標系與Cocoa的座標系顛倒了。 (真的,Cocoa對我來說是顛倒的,但這只是一個慣例)。

我自己一直都忘記這個!

1

有兩件事情要記住......

  • cocos2d的座標系的原點是左下角。
  • 默認情況下,顯示元素的錨點是它們的中心。

所以我這是怎麼解決這個問題:

設置元素的定位點是左下角爲好。

[block setAnchorPoint:ccp(0, 0)]; 

在ccTouchesBegan中使用convertCoordinate。

-(BOOL)ccTouchesBegan:(NSSet *)touches withEvent:(UIEvent *)event 
{ 
    UITouch *touch = [touches anyObject]; 
    CGPoint pt = [touch locationInView:[touch view]]; 
    CGPoint ptConv = [[Director sharedDirector] convertCoordinate:pt]; 
} 

計算元素的矩形,比較...

CGSize size = [block contentSize]; 
CGPoint point = [block position]; 
rect = CGRectMake(point.x, point.y, size.width, size.height); 

if (CGRectContainsPoint(rect, ptConv)) 
{ 
    // touched 
} 

它看起來像你缺少的一個步驟是改變錨點。

如果你不喜歡改變錨點,您需要更改矩形的計算方法;加減寬度和高度的一半。

希望它有幫助。