7
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

子Nodeの数を再帰的に全て数える(cocos2dx v3.2 以降)

7
Last updated at Posted at 2014-11-06

ただ1階層下にある子Nodeの数を数えたいだけなら、以下のようにするだけ

auto childrenNum = node->getChildren().size();

ある Node にぶら下がっている NodeTree 全てを再帰的に数えたいなら、 enumerateChildren を使えば出来た(cocos2dx v3.2 以降!)

auto rootNode = cocos2d::Node::create();

auto child1 = cocos2d::Node::create();
auto child2 = cocos2d::Node::create();

auto grandChild1 = cocos2d::Node::create();
auto grandChild2 = cocos2d::Node::create();

rootNode->addChild(child1);
rootNode->addChild(child2);

child1->addChild(grandChild1);
child1->addChild(grandChild2);

/**
 *  Node構成は以下のようになってる
 *  
 *  rootNode
 *    + child1
 *      + grandChild1
 *      + grandChild2
 *    + child2
 */

上記のような構成の場合、rootNode->getChildren().size() の結果は 2 になる。
孫Nodeも含めて 4 を取得するためには、以下のような処理で実現できた。

int countChildrenRecursively(cocos2d::Node* rootNode) {
    int count = 0;
    rootNode->enumerateChildren("//.*", [&count](cocos2d::Node*) -> bool {
        count++;
        return false;
    });
    return count;
}

int childrenCount = countChildrenRecursively(rootNode); // 4になるはず

enumerateChildren の第一引数には探したいNodeの name を指定するんだけど、
頭に // を加える事で検索が Recursive になる。
name 部分には正規表現が使えるので、//.* と指定すれば Recursive に全てのNodeが対象になる。

7
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?