[cocos2d-x]关于定时器

2023-02-22,

什么是定时器

定时器的作用就是每隔一段时间,就执行一段自定义的动作,比如飞机向前方移动,子弹的移动等等。该函数定义在CCNode头文件中,基本上cocos2dx中所有的东西都能够使用定时器。

定时器的分类

第一种:scheduleupdate()默认定时器

该定时器开启函数与update()函数配套使用,update方法是每一帧执行一次,所以如果默认每秒60帧,那么每秒就执行60次。

使用方法:

class Test:public Scene
{
....
virtual void update(float f);
....
}
bool init()
{
Scene::create();
this->scheduleupdate();//开始进行update操作
}
void update(float f)
{
....//进行的一些自定义操作
}

第二种:schedule()自定义计时器

这种定时器的灵活性更加大,比如设置新的函数代替update函数,定义刷新的次数和间隔。

    this->schedule(schedule_selector(GameTest::update),1,1,1);
@param selector The SEL_SCHEDULE selector to be scheduled.
* @param interval Tick interval in seconds. 0 means tick every frame. If interval = 0, it's recommended to use scheduleUpdate() instead.
* @param repeat The selector will be executed (repeat + 1) times, you can use CC_REPEAT_FOREVER for tick infinitely.
* @param delay The amount of time that the first tick will wait before execution.

第三种:scheduleOnce()一次性定时器

顾名思义,这种定时器只会执行一次。

this->scheduleOnce(schedule_selector(GameTest::update), 1.1);
* @param selector The SEL_SCHEDULE selector to be scheduled.
* @param delay The amount of time that the first tick will wait before execution.

定时器的通用操作

    this->unschedule(schedule_selector(GameTest::update));
//取消自定义的函数
this->unscheduleAllSelectors();
//取消所有的自定义函数
this->unscheduleUpdate();
//取消默认的update函数
this->unscheduleAllCallbacks();
//取消所有的自定义函数,lambda函数,update函数,但是action动作不会被影响
this->pauseSchedulerAndActions();
//暂停定时器和动作
this->resumeSchedulerAndActions();
//恢复定时器和动作

[cocos2d-x]关于定时器的相关教程结束。

《[cocos2d-x]关于定时器.doc》

下载本文的Word格式文档,以方便收藏与打印。