CCNode recursive getChildByTag

烂漫一生 提交于 2019-12-24 10:34:36

问题


As far as I understand the CCNode::getChildByTag method only searches among direct children.

But is there any way to recursively find a CCNode's child by tag in all its descendant hierarchy ?

I'm loading a CCNode from a CocosBuilder ccb file and I'd like to retrieve subnodes knowing only their tags (not their position/level in the hierarchy)


回答1:


One way - to create your own method. Or create category for CCNode with this method. It will look like smth like this

- (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;
}

Add this method to the CCNode category. You can create category in any file you want but I recommend to create separate file with this category only. In this case any other object where this header will be imported, will be able to send this message to any CCNode subclass.

Actually, any object will be able to send this message but it will cause warnings during compilation in case of not importing header.




回答2:


Here would be a cocos2d-x 3.x implementation for a recursive getChildByTag function:

/** 
 * 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;
}

As an option you can also pass in the type of the node searched for as an argument.



来源:https://stackoverflow.com/questions/13309180/ccnode-recursive-getchildbytag

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!