CCNode递归getChildByTag

时间:2012-11-09 13:40:03

标签: cocos2d-iphone ccnode

据我了解,CCNode::getChildByTag方法只搜索直接儿童。

但有没有办法在其所有后代层次结构中递归地找到CCNode的子标记?

我正在从CocosBuilder ccb文件加载一个CCNode,我想要只知道它们的标签(而不是它们在层次结构中的位置/级别)来检索子节点。

2 个答案:

答案 0 :(得分:5)

一种方法 - 创建自己的方法。或者使用此方法为CCNode创建类别。看起来像这样的smth

- (CCNode*) getChildByTagRecursive:(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子类。

实际上,任何对象都可以发送此消息,但如果不导入标题,它将在编译期间引发警告。

答案 1 :(得分: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;
}

作为选项,您还可以将搜索到的节点类型作为参数传递。

相关问题