2011-03-30 26 views
2

我想在CCNode子類中使用類似-(void)removeAllChildrenWithTag:(int)tag的方法。你會怎麼做?Cocos2d RemoveAllChildrenWithTag

我將我的遊戲的每一輪添加一些精靈到這個節點,並且在一輪結束後我想刪除它們。我認爲給他們所有的同一個標籤會很好,所以我可以通過標籤去除它們。但是隻有一種方法可以刪除帶有標籤的一個孩子。

我知道我可以調用這種方法,直到沒有孩子離開,但我認爲它會很慢。有沒有更好的解決方案,像遍歷整個孩子,並刪除每個提到的標籤?我不知道該怎麼做,因爲你不能移除for(* in *) -loop中的任何孩子。

希望你能幫助我。 :)

回答

8

是的..我認爲迭代兒童數組和刪除指定的標記兒童將是最簡單的。 這是一些代碼。

CCNode *aChild; 
while((aChild=[parentNode getChildByTag:aTag]) != nil) 
    [parentNode removeChild:aChild cleanup:YES]; 
+0

那豈不是更好地調用[aChild removeFromParentAndCleanup:YES]而不是[parentNode removeChild之:achild清理:是],會嗎? – ChaosCoder 2011-03-30 08:48:22

+0

親愛的我建議你使用API​​,因爲它是開源的。 這裏是removeFromParentAndCleanup的實現: - (無效)removeFromParentAndCleanup:(BOOL)清理 { \t [PARENT_ removeChild之:自我清理:清理]; } – 2011-03-30 08:49:54

+0

哦,對。沒有看到。感謝您的回答! – ChaosCoder 2011-03-30 08:55:10

0

[self removeChildByTag:1 cleanup:YES];


這將消除只有一個孩子 以下是完整的實施方法

-(void) removeChildByTag:(int)aTag cleanup:(BOOL)cleanup 
{ 
    NSAssert(aTag != kCCNodeTagInvalid, @"Invalid tag"); 

    CCNode *child = [self getChildByTag:aTag]; //here it is simply getting a single chil 

    if (child == nil) 
     CCLOG(@"cocos2d: removeChildByTag: child not found!"); 
    else 
     [self removeChild:child cleanup:cleanup]; 
} 


-(CCNode*) getChildByTag:(int) aTag 
{ 
    NSAssert(aTag != kCCNodeTagInvalid, @"Invalid tag"); 

    CCNode *node; 
    CCARRAY_FOREACH(children_, node){ 
     if(node.tag == aTag) 
      return node; //as it finds the first child with the specified tag it will return 
    } 
    // not found 
    return nil; 
}