[SOLVED] Get a BoundingBox from a DrawNode object is possible? I afraid not!

We can use DrawNode to draw some useful information for debugging, or something more sophisticated as a health bar above char’s head or just something we need to hit by a click that is my case.

My issue consist to retrieve the BoundingBox from a rectangle made by a DrawNode. All information I get is 0, nothing about position (x, y) and its size (width, height). I need it to create a touch event to check if user is touching inside the rectangle’s area or not.

The process to create the the rects:

DrawNode* Player::createRect(cocos2d::Vec2 p1, cocos2d::Vec2 p2, cocos2d::Vec2 p3, cocos2d::Vec2 p4) {
    float alpha = 0.8;
    auto rect = DrawNode::create();
    
    Vec2 vertices[] = {p1, p2, p3, p4};
    
    rect->setAnchorPoint(Vec2(0, 0));
    rect->drawPolygon(vertices, 4, Color4F(1.0, 1.0, 1.0, alpha), 1, Color4F(0.2, 0.2, 0.2, alpha));
    _sprite->addChild(rect, -1);
    
    return rect;
}

Above function is working as well, I create the rects and add them as a child to a player’s sprite. The snippet below shows up how I’m trying to capture the bounding of these rects by user’s touch.

…

if (_player->rectUp.box->getBoundingBox().containsPoint(touchLocation))
    direction = Direction::UP;
else if (_player->rectDown.box->getBoundingBox().containsPoint(touchLocation))
    direction = Direction::DOWN;
else if (_player->rectLeft.box->getBoundingBox().containsPoint(touchLocation))
    direction = Direction::LEFT;
else if (_player->rectRight.box->getBoundingBox().containsPoint(touchLocation))
    direction = Direction::RIGHT;

…

How can I get the exactly dimension of these rects even bounding box returning nothing for me? Need I to replace it to a baked sprite to make cocos2d-x understand the position and it’s size? I still want to use DrawNode to achieve this if possible.

By the look of it there’s no to get it’s true size currently. I can image 3 options:

  1. As you said, just use a sprite instead. Simple and easy.
  2. Manually track the size of the DrawNode yourself. When you draw to it, record in a variable the new size of the DrawNode, or even use the DrawNode’s setContentSize method. (I imagine it has one and that it won’t interfere with anything.)
  3. Create a subclass of DrawNode and whenever a drawing function is called, automatically adjust the node’s content size to match.

I have to every user’s touch recreate all rectangles I had already created with updated position’s information, this is not the best way I guess but works for now.

Hi, setContentSize actually works very well. I’m using DrawNode class to create my prototypes without sprites and touch events work great.

2 Likes