【爱上cocos2d-x之十七】scheduleOnce定时器只调用一次

发现定时器的功能还真是蛮强大的,但是如果我们现在有一个需求:希望在几秒之后调用一个函数,而不是每个几秒调用这个函数。
那么,我们这时可以利用scheduleOnce可以来完成,顾名思义,Once,你懂的。
首先,我们新建一个项目为HelloSchedule,打开头文件添加oneUpdate函数


class HelloWorld : public cocos2d::CCLayer
{
public:
    // Here's a difference. Method 'init' in cocos2d-x returns bool, instead of returning 'id' in cocos2d-iphone
    virtual bool init();  

    // there's no 'id' in cpp, so we recommend returning the class instance pointer
    static cocos2d::CCScene* scene();
      
    // implement the "static node()" method manually
    CREATE_FUNC(HelloWorld);

    /* 回调函数 */
    void  oneUpdate(float dt);

};

打开cpp文件,添加代码如下:


// on "init" you need to initialize your instance
bool HelloWorld::init()
{
    if ( !CCLayer::init() )
    {
        return false;
    }
    
    /* 指定3秒之后执行一次函数 */
    this->scheduleOnce(schedule_selector(HelloWorld::oneUpdate),3.0f);

    return true;
}

void HelloWorld::oneUpdate(float dt)
{
    CCLOG("call oneUpdate once");
}

在Debug模式下运行,效果如下:

3秒之后,仅仅看到这一条。
到这里为止,我们通过4篇简短的文章把定时器介绍完了。

你都没有链接。只看到这一篇怎么找前面的。

现在已经全部贴出来了,不断更新中,欢迎关注 :7: :7: :7:

同问 为什么只调用一次?

如果 再回调函数 this->scheduleOnce(schedule_selector(HelloWorld::oneUpdate),3.0f); ,调用自己呢? 为什么也只调用一次?