【问题标题】:CCNode recursive getChildByTagCCNode 递归 getChildByTag
【发布时间】:2012-11-09 13:40:02
【问题描述】:

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

但是有什么方法可以在 CCNode 的所有后代层次结构中通过标签递归地找到一个 CCNode 的子节点?

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

【问题讨论】:

  • 如果需要,您可以轻松实现递归的getChildByTag 访问整个层次结构。

标签: cocos2d-iphone ccnode


【解决方案1】:

一种方法 - 创建自己的方法。或使用此方法为 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 子类。

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

【讨论】:

  • 你没有递归调用它
  • 这个方法会在哪个类?
  • 哦,好的。到目前为止,我从来没有类别标题,我不是一个真正的 Objective C 大师:)。感谢您的提示
【解决方案2】:

这将是一个递归 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;
}

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

【讨论】:

    猜你喜欢
    • 2015-01-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多