【cocos2d-x游戏开发】定时事件

【cocos2d-x游戏开发】定时事件,第1张

概述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 poi 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" >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);
总结

以上是内存溢出为你收集整理的【cocos2d-x游戏开发】定时事件全部内容,希望文章能够帮你解决【cocos2d-x游戏开发】定时事件所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://www.outofmemory.cn/web/1005247.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-22
下一篇 2022-05-22

发表评论

登录后才能评论

评论列表(0条)

保存