2012-11-09 23 views
1

據我瞭解CCNode::getChildByTag方法只在直接的孩子之間搜索。CCNode遞歸getChildByTag

但是有沒有什麼辦法通過標籤在其所有後代層次結構中遞歸查找CCNode的子級?

我加載從CocosBuilder CCB文件CCNode,我想找回子節點只知道他們的標籤(在層次結構中沒有他們的位置/水平)

+0

如果你需要,你可以很容易地實現一個遞歸的'getChildByTag'來訪問整個層次結構。 – sergio

回答

4

一種方法 - 創建自己的方法。或者用此方法爲CCNode創建類別。它會看起來像這樣水手

- (CCNode*) getChildBuTagRecursive:(int) tag 
{ 
    CCNode* result = [self getChildByTag:tag]; 

    if(result == nil) 
    { 
     for(CCNode* child in [self children]) 
     { 
      result = [child getChildByTagRecursive:tag]; 
      if(result != nil) 
      { 
       break; 
      } 
     } 
    } 

    return result; 
} 

將此方法添加到CCNode類別。您可以在任何需要的文件中創建類別,但我建議僅使用此類別創建單獨的文件。在這種情況下,將會導入此頭的任何其他對象將能夠將此消息發送給任何CCNode子類。

實際上,任何對象都能夠發送這個消息,但是如果沒有導入頭文件,編譯過程中會導致警告。

+0

你不是遞歸地調用它 – LearnCocos2D

+0

好吧,現在你做:) – LearnCocos2D

+0

是啊)檢查答案並修復它=)thx =) – Morion

0

這裏將是一個遞歸getChildByTag功能是Cocos2d-X 3.x的實現:

/** 
* Recursively searches for a child node 
* @param typename T (optional): the type of the node searched for. 
* @param nodeTag: the tag of the node searched for. 
* @param parent: the initial parent node where the search should begin. 
*/ 
template <typename T = cocos2d::Node*> 
static inline T getChildByTagRecursively(const int nodeTag, cocos2d::Node* parent) { 
    auto aNode = parent->getChildByTag(nodeTag); 
    T nodeFound = dynamic_cast<T>(aNode); 
    if (!nodeFound) { 
     auto children = parent->getChildren(); 
     for (auto child : children) 
     { 
      nodeFound = getChildByTagRecursively<T>(nodeTag, child); 
      if (nodeFound) break; 
     } 
    } 
    return nodeFound; 
} 

作爲一個選項,您還可以通過在節點的類型搜索作爲參數。