1

据我了解,该CCNode::getChildByTag方法仅在直接子代中搜索。

但是有没有办法在所有后代层次结构中通过标签递归地找到 CCNode 的子节点?

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

4

2 回答 2

5

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

- (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 子类。

实际上,任何对象都可以发送此消息,但如果不导入标头,它会在编译过程中引起警告。

于 2012-11-09T14:02:52.053 回答
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;
}

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

于 2014-07-30T09:30:56.577 回答