How to properly subclass DrawNode?

I have a really simple scene:

bool BallScene::init()
{
    auto size = Director::getInstance()->getVisibleSize();
    auto center = Vec2(size.width / 2, size.height / 2);
    auto ball = DrawNode::create();
    ball->drawDot(Vec2::ZERO, 128, Color4F::YELLOW);
    this->addChild(ball);

    auto listener = EventListenerTouchOneByOne::create();
    listener->onTouchBegan = [ball] (Touch *touch, Event *event) -> bool {
        auto loc = touch->getLocation();
        auto move = MoveTo::create(1, loc);
        auto easing = EaseOut::create(move, 2);
        ball->stopAllActions();
        ball->runAction(easing);
        return true;
    };

    this->getEventDispatcher()->addEventListenerWithSceneGraphPriority(listener, this);
    return true;
}

So far it works as intended. Next, I’m trying to subclass the DrawNode class and create a Ball node like this:

class Ball : public DrawNode
{
public:
    CREATE_FUNC(Ball);
    virtual bool init()
    {
        drawDot(Vec2::ZERO, 128, Color4F::YELLOW);
        return true;
    }
};

But when I try to use it in my scene, nothing gets displayed at all.

auto ball = Ball::create();
this->addChild(ball);

So my question is what I’m doing wrong and why can’t I initialize my DrawNode contents inside init()?

2 Likes

My first intuition would be that you need to call the parent class’s init function. Try:

virutal bool init() {
  if (!DrawNode::init()) {
    return false;
  }

  drawDot(Vec2::ZERO, 128, Color4F::YELLOW);
  return true;
}

DrawNode does a lot in its init function by the look of it, so you don’t want to skip calling it.

3 Likes

Now it works! Thank you so much! :slight_smile:

1 Like