Bounding Box on sprite with children

Hello,
Need help regarding the functionality of Sprite::getBoundingBox
i am trying to accomplish the simple physics mechanic for my game thus not using the Physics engine

the problem does not exists if the sprite have / assigned a texture, we could retrieve the bounding box correctly(the width and the height is not zero)

but when i try to create a hierarchical type of sprite, i could not retrieve the correct bounding box on the parent…

example code:

auto p = Sprite::create();
layer->addChild(p);

auto s1 = Sprite::create("image1.png");
auto s2 = Sprite::create("image2.png");

s1->setPosition(Vec2(20.f, 10.f))
s2->setPosition(Vec2(100.f, 100.f));

p->addChild(s1);
p->addChild(s2);

p->setPosition(Vec2(10.f, 100.f));

auto aabb = p->getBoundingBox() //---> the aabb's width and height are zero

how to get the correct boundingbox?
Thanks in advance guys!

As far as I know, the bounding box of a node doesn’t consider child nodes. So I am afraid you have to loop through the child sprites, get their bounding boxes etc…

For example like this:

    auto boundingBox = p->getBoundingBox();
    for (auto && child : p->getChildren()) {
        boundingBox.unionWithRect(child->getBoundingBox());
    }

If your child nodes have children too, you will have to do this recursive of course…

This is how the recursive version could look like:

    std::function<Rect(Node*)> getChildrenBoundingBox = [&](Node* node) {
        auto rect = node->getBoundingBox();
        for (auto && child : node->getChildren()) {
            rect.unionWithRect(getChildrenBoundingBox(child));
        }
        return rect;
    };
    
    auto boundingBox = getChildrenBoundingBox(p);

There’s one in the utils namespace (ccUtils.cpp).

Node* node;
Rect bboxIncludeChildren = utils::getCascadeBoundingBox(node);
3 Likes

This is a good thing to add to the Programmers Guide.

hi @yohanip

Is it not true that since the Sprite doesn’t contain any texture then it will just be like any other Node and it’s bounding box width and height will return 0.

AFAIK, a Node bounding box will give 0 width and height.
Please feel free to correct me if I am wrong.

Thank you.