Problem with setting position of DrawNode

I most likely am doing something wrong, but I can’t quite figure how to update the position of a DrawNode correctly.

I created a bare bones project to simulate this.

I have a sprite, and a drawn node. I create the Sprite, set its position and add it to the scene. Next I create the DrawNode, use the rect origin of the of the sprites bounding box, and for the destination I use the sprites position.

Now if I don’t call drawNode->setPosition(), the drawnode is where I would expect it, but as soon as call drawNode->setPosition(), the drawnode is offset quite a bit.

Also, the drawNode is one quarter of the size I would expect…

Any ideas?

Heres a link to a quick video demonstrating. video

Heres the simple code

// on "init" you need to initialize your instance
bool HelloWorld::init()
{
    //////////////////////////////
    // 1. super init first
    if ( !Layer::init() )
    {
        return false;
    }

    this->sprite = Sprite::create("16x16_pixel.png");
    sprite->setPosition(Vec2(100, 100));
    this->addChild(this->sprite);

    this->drawNode = DrawNode::create();
    drawNode->drawRect(sprite->getBoundingBox().origin, sprite->getPosition(), Color4F(1, 0, 0, 1));
    this->addChild(this->drawNode);

    this->scheduleUpdate();

    return true;
}

void HelloWorld::update(float delta)
{

    this->sprite->setPositionX(this->sprite->getPositionX() + 0.1);
    this->drawNode->setPositionX(this->sprite->getPositionX());

}

You draw your rectangle at the position of the sprite - but the sprite’s position is relative to ‘this’ (the hello world layer) but your rectangle’s position is relative to the drawNote itself

Change the drawRect() to draw at Vec2(0,0) and you’ll see what I mean…

Thanks for the reply!

I think I understand. By doing the following, the drawNode moves as expected:

void HelloWorld::update(float delta)
{
    this->sprite->setPositionX(this->sprite->getPositionX() + 0.1);
    this->drawNode->setPositionX(this->drawNode->getPositionX() + 0.1);
}

Now, why is it that the draw rect is a quarter of the size of the bounding box?

Because you told it so in your code.

The origin of your Sprite is centered. It’s position of 100/100 is from it’s center.

You draw the rectangle from the Sprite’s bounding-box origin, which is from the bottom left corner, to the Sprite’s position, which is it’s center.
The rectangle is drawn from the origin to the destination, which in your case is from the bottom left corner of the Sprite to the center of the Sprite. It’s exactly what you see in the screenshot.

Got it! Thanks for the great explanation! Thats what I really like about cocos2d-x. A great community!

1 Like