【cocos2d-x游戏开发】定时事件
发布时间:2020-12-14 19:11:49 所属栏目:百科 来源:网络整理
导读:1.schedule和update 在init函数里面输入以下代码 this-scheduleUpdate(); 在头文件里面加入以下代码 class HelloWorld : public cocos2d::Layer{public: // there's no 'id' in cpp,so we recommend returning the class instance pointer static cocos2d::S
1.schedule和update
在init函数里面输入以下代码
this->scheduleUpdate();在头文件里面加入以下代码 class HelloWorld : public cocos2d::Layer { public: // there's no 'id' in cpp,so we recommend returning the class instance pointer static cocos2d::Scene* createScene(); // Here's a difference. Method 'init' in cocos2d-x returns bool,instead of returning 'id' in cocos2d-iphone virtual bool init(); // a selector callback void menuCloseCallback(cocos2d::Ref* pSender); // implement the "static create()" method manually CREATE_FUNC(HelloWorld); virtual void update(float dt); //新输入的代码 };然后在源文件里面输入下面这个函数 void HelloWorld::update(float dt) { log("update"); }然后,在日志输出窗口可以看到以下内容
就这样,已经实现了定时器最简单的功能,this->scheduleUpdate()函数是为了把当前节点(如Layer)添加到队列中,只要把节点添加到队列中,那么这个节点就会在游戏运行的
每一帧都调用一次update函数。update函数里面有一个float dt参数,意思就是上次调用这个函数到本次调用这个函数中间间隔了多少秒。
2.schedule和回调函数
这次我们不调用update函数,我们调用自己的函数。当我们调用scheduleUpdate时,系统默认每帧去掉用update函数。
我们在init函数里面写下这句代码
this->schedule(schedule_selector(HelloWorld::mutUpdate)); 然后在源文件里面写上自己定义的函数 <pre name="code" class="cpp">void HelloWorld::mutUpdate(float dt) { log("MutUpdate"); } 我们在头文件里面说明一下 void mutUpdate(float dt); 然后我们会看到下面的结果
Cocos2d-x在指定回调函数时都需要使用*selector的形式,比如我们要知道schedule的回调函数,则使用schedule_selector,要指定按钮的回调函数则使用callfunc_selector等。
常用的selector如下:
schedule_selector:常用于定义定时器回调函数,函数无参数;
callfunc_selector:常用于定义动作回调函数,函数无参数;
callfuncN_selector:常用于定义动作回调函数,函数带一个Node*参数;
callfuncND_selector:常用于定义动作回调函数,函数带一个Node*参数和一个void*参数(任意类型);
menu_selector:常用于定义动作回调函数,带一个CCObject*参数。
虽然这次我们能够在每一帧都调用我们自己定义的函数,但是不能认为这是定时器,我们稍微修改一次
this->schedule(schedule_selector(HelloWorld::mutUpdate),2.0f); void HelloWorld::mutUpdate(float dt) { log("MutUpdate dt=%f",dt); }
我们加了一个参数,参数类型是float,单位是秒。在mutUpdate函数里面打印dt的值。
3.unSchedule
如果我们要取消update函数的调用,我们就用到unSchedule。
void HelloWorld::update(float dt) { log("update"); this->unscheduleUpdate(); }我们在update函数里面加入这句代码 this->unscheduleUpdate();然后我们看到日志只输出一句update就停止了。
如果我们想停止自定义的update哈市南湖也是类似的操作,下面是代码
void HelloWorld::mutUpdate(float dt) { log("MutUpdate dt=%f",dt); this->unschedule(schedule_selector(HelloWorld::mutUpdate)); }如果要停止所有的update函数,我们只需要一行代码: this->unscheduleAllSelectors(); 4.scheduleOnce和回调函数
scheduleOnce,顾名思义,once代表只执行一次,第二个参数是延迟时间,单位是秒,表示多少秒之后开始执行这个函数,
并且只执行一次。
this->unschedule(schedule_selector(HelloWorld::mutUpdate),2.0f); (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |