调度器(scheduler)是主要是为游戏提供定时事件和定时服务。常常用来游戏的一些定时处理的功能,例如一些逻辑判断,碰撞检测等。 Cocos2dx提供了三种常用的调度器(scheduler)来让我们使用
//默认调度器: schedulerUpdate() //自定义调度器: schedule(SEL_SCHEDULE selector, float interval, unsigned int repeat, float delay) //单次调度器: scheduleOnce(SEL_SCHEDULE selector, float delay)1默认调度器(schedulerUpdate) 默认调度器使用Node的刷新事件update方法,该方法在每帧绘制之前都会被调用一次。由于每帧之间时间间隔较短,所以每帧刷新一次已足够完成大部分游戏过程中需要的逻辑判断。
我们在使用默认调度器(schedulerUpdate)时候,需要重载Node的update方法来执行自己的逻辑代码。如果需要停止这个调度器,可以使用unschedulerUpdate()方法。 //取消默认调度 unschedulerUpdate() 使用时候首先在.h文件里重写update方法:void update(float dt) 。 在调用的地方直接使用scheduleUpdate()方法调用update的实现。例如:
HelloWorldScene.h void update(float dt) override; HelloWorldScene.cpp bool HelloWorld::init() { ... scheduleUpdate(); return true; } void HelloWorld::update(float dt) { log("update"); }结果:
cocos2d: update cocos2d: update cocos2d: update cocos2d: update2自定义调度器(scheduler) 有时候引擎自带的调度器并不适合我们的需要,所以需要自己定义调度器。而cocos2dx则提供了此方法。 由于引擎的调度机制,自定义时间间隔必须大于两帧的间隔,否则两帧内的多次调用会被合并成一次调用。所以自定义时间间隔应在0.1秒以上
schedule(SEL_SCHEDULE selector, float interval, unsigned int repeat, float delay) 第一个参数selector即为你要添加的事件函数。 第二个参数interval为事件触发时间间隔。 第三个参数repeat为触发一次事件后还会触发的次数,默认值为kRepeatForever,表示无限触发次数。 //取消该调度器 unschedule(SEL_SCHEDULE selector, float delay)以下是测试代码
HelloWorldScene.h void updateCustom(float dt); HelloWorldScene.cpp bool HelloWorld::init() { ... schedule(schedule_selector(HelloWorld::updateCustom), 1.0f, kRepeatForever, 0); return true; } void HelloWorld::updateCustom(float dt) { log("Custom"); }在控制台你会看到每隔1秒输出以下信息
cocos2d: Custom cocos2d: Custom cocos2d: Custom cocos2d: Custom cocos2d: Custom3.单次调度器(schedulerOnce) 游戏中某些场合,你只想进行一次逻辑检测,Cocos2d-x同样提供了单次调度器。 该调度器只会触发一次
//取消该触发器 unschedule(SEL_SCHEDULE selector, float delay)以下代码用来测试该调度器:
HelloWorldScene.h void updateOnce(float dt); HelloWorldScene.cpp bool HelloWorld::init() { ... scheduleOnce(schedule_selector(HelloWorld::updateOnce), 0.1f); return true; } void HelloWorld::updateOnce(float dt) { log("Once"); }这次在控制台你只会看到一次输出
cocos2d: Once scheduleOnce(SEL_SCHEDULE selector, float delay) //第一个参数是执行的函数 //表示几秒之后执行,并且只会执行一次总结: 1.默认调度器: 直接调用schedulerUpdate() 函数,同时重写update方法,这样就是在用的地方直接使用scheduleUpdate()方法调用update的实现 2 自定义调度器: 调schedule(SEL_SCHEDULE selector, float interval, unsigned int repeat, float delay)函数 ,具体实现在selector函数中去执行 3.单次调度器: 调scheduleOnce(SEL_SCHEDULE selector, float delay)函数 ,具体实现在selector函数中去执行 补充:
scheduler.unscheduleAllCallbacksForTarget(this);//取消指定节点的指定计划