Search code examples
cocos2d-xcocos2d-x-3.0cocos2d-x-2.x

Node loaded from .csb has bounding box size 0


I have created Node ( with images and labels inside ) and I instantiate and add to scene ( in C++ code )

    auto item_one = CSLoader::createNode("item.csb");
    sprite->addChild(item_one);
    auto r = item_one->getBoundingBox();

and it is visible but r always has width and height equal to zero. That is a reason why I cannot fetch click on that item. Why is bounding box zero and how to change that ? In cocos studio Node for item has dimensions of 542 x 542 but. Can anyone help ?


Solution

  • The CSLoader::createNode("fileName.csb") loads the entire scene/layer (depending what you created). If you want the dimensions of a specific child use:

    auto imageNode = item_node->getChildByName("NameOfChildInCocostudio");
    auto spriteImage = dynamic_cast<Sprite*>(imageNode);
    auto spriteBoundingBox = spriteImage->getBoundingBox();
    

    At this point you should get the width and height of the image. If you want the size it appears at you have to multiply the bounds with the node scale. Use the code below to do that.

    auto onScreenWidth = spriteBoundingBox.width * spriteNode->getScaleX();
    auto onScreenHeight = spriteBoundingBox.height * spriteNode->getScaleY();
    

    Let me know if this helps.