2013-03-18 25 views
0

使用下面的方法,當檢查它們是否相交時,如何引用特定的精靈?如何在使用Cocos2d碰撞檢測時引用sprites?

- (void)update:(ccTime)dt { 
    for (CCSprite *sprite in movableSprites) { 
     if (CGRectIntersectsRect(sprite.boundingBox, sprite.boundingBox)) { 
      break; 
     } 
    } 
} 

看來,所有精靈都在moveableSprites對象可用的,但我不知道如何檢查是否存在特定的精靈發生碰撞......我不知道如何來指代他們。如果有更簡單的方法來執行碰撞檢測,我很感興趣。

回答

3

看來你的代碼上面將始終返回true,因爲你是檢查是否精靈碰撞精靈,並且由於它們是同它總是會的外接矩形框。

if (CGRectIntersectsRect(sprite.boundingBox, sprite.boundingBox)) {// 
     break; 
    } 

應該比較一個不同的精靈不相同的精靈。

if (CGRectIntersectsRect(sprite.boundingBox, otherSprite.boundingBox)) {// 
     break; 
    } 

如果這不能回答你的問題,也許你正在尋找避免通過數組枚舉?如果是這種情況,請嘗試使用標籤。有點像下面。

CCSprite *aSprite = [CCSprite spriteWithFile:@"hurdle1.png"]; 

    [self addChild:aSprite tag:2]; 

現在[自getChildByTag:2]可以採取精靈 的地方,你可以再補充boundingBox的檢查碰撞,如下圖所示。

if (CGRectIntersectsRect([self getChildByTag:2].boundingBox, checkSprite.boundingBox)) {// 
     break; 
    }