Cocos2d-JS使用scheduler小结
所使用的环境
Win7 64位、Cocos2d-JS v3.1、Cocos Code IDE v1.0.0.Final
正文
在Cocos2d-JS中使用scheduler主要分为两种方式:一种是直接使用延时函数,如scheduleCallbackForTarget、scheduleOnce等;另一种是在每帧的更新函数里面进行控制。
1. 第一种:直接使用函数的方式
这里主要探讨使用过程中需要注意的地方,关于函数参数,官方的API文档已经有详细介绍(API查询地址:http://www.cocos2d-x.org/reference/html5-js/V3.0/index.html ,在左上角输入cc.scheduler)。
以this.scheduleOnce(回调函数, 延迟时间)为例,需要特别注意回调函数的使用。
1.1 回调函数无参的情况
当回调函数没有参数时,示例代码如下:
noParameter : function() {
cc.log("NO parameter !!");
}
使用时,只写函数名,不带括号(假设延迟时间为3秒):
this.scheduleOnce(this.noParameter, 3);
// 回调函数带不带this视其作用域而定
1.2 回调函数有参的情况
当回调函数有参数时,示例代码如下:
haveParameter : function(i) {
cc.log("Have parameter " + i);
}
为了实现正常的延时效果,需要在外面套一层function name() {}再调用。否则,函数会在程序一开始就运行,无法实现延时。实际上,这样做就变成了无参函数调用有参函数的情况。示例如下(假设延迟时间为5秒):
this.scheduleOnce(function a() {
this.haveParameter(1111);
// 回调函数带不带this视其作用域而定
}, 5);
2. 第二种:在每帧更新函数里进行控制
以layer为例,在初始化时(在ctor函数return true前,onEnter等其他地方也可以,但最好在初始化时)添加如下代码:
this.scheduleUpdate();
// 表示使用每帧更新函数
接着重写layer的update方法。这里先定义了一个作用域在layer的变量time,示例代码如下:
update : function(dt) {
this.time += dt;
// dt为每一帧执行的时间,把它加起来等于运行了多长时间
if (this.time > 7) {
cc.log("每7秒显示一次");
this.time = 0;
// 每7秒重置为0,以达到循环显示
}
// cc.log(this.time);
// time的当前时间
}