据我所知,CCNode::getChildByTag方法只在直接子对象中搜索。
但是,有没有办法在CCNode的所有后代层次结构中通过标记递归地找到它的子节点呢?
我正在从CocosBuilder ccb文件加载一个CCNode,我想检索只知道它们的标签的子节点(不知道它们在层次结构中的位置/级别)。
发布于 2012-11-09 22:02:52
一种方法--创建自己的方法。或者使用此方法为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子类。
实际上,任何对象都可以发送此消息,但在不导入头部的情况下,它会在编译过程中引发警告。
发布于 2014-07-30 17:30:57
下面是递归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;
}作为一个选项,您还可以将搜索到的节点类型作为参数传入。
https://stackoverflow.com/questions/13309180
复制相似问题