schedule用法主要分为两种方式,一种是直接用延时函数,比如scheduleCallbackForTarget,scheduleOnce等;另外一种就是在每帧的更新函数里面进行控制。
1. 第一种直接使用函数的方式
以this.scheduleOnce(回调函数,延迟时间)为例,这里要注意的是回调函数的使用。
1.1 当回调函数为无参时,如:
1
2
3
|
noParameter :
function
() {
cc.log(
"NO parameter !!"
);
},
|
那么用的时候写函数名,不带括号而使用了(假如延迟时间为3秒):
1
|
this
.scheduleOnce(
this
.noParameter, 3);
//回调函数带不带this视其作用域而定
|
1.2 当回调函数为有参时,如:
1
2
3
|
haveParameter :
function
(i) {
cc.log(
"Hava parameter "
+ i);
},
|
那么使用的时候为了能正常延时,需要在外面套一层function name(){},再调用,不然就会在程序一开始时运行,没有延时效果,不过这样做,实际上变成了上面无参时的情况,在一个无参的函数里面调用其他函数而已:
1
2
3
|
this
.scheduleOnce(
function
a() {
this
.haveParameter(1111);
//回调函数带不带this视其作用域而定
}, 5);
|
2. 第二种在每帧更新函数里进行控制
以layer为例,在初始化的时候(ctor函数return true 前,onEnter等其他地方也可以,不过最好在初始化时)添加:
1
|
this
.scheduleUpdate();
//表示使用每帧更新函数
|
接着重写layer的update方法:(这里先定义了一个作用域在layer的变量time)
1
2
3
4
5
6
7
8
|
update :
function
(dt) {
this
.time += dt;
//dt为每一帧执行的时间,把它加起来等于运行了多长时间
if
(
this
.time > 7){
cc.log(
"每7秒显示一次"
);
this
.time = 0;
//每7秒重置为0,以达到循环显示
}
//cc.log(this.time);//time的当前时间
},
|
3.全部用法
1
2
3
4
5
6
7
8
9
10
11
|
var
node =
new
cc.Node();
// node的update函数将会在每一帧被执行
node.scheduleUpdate();
// callback回调函数会重复得在每个interval时间间隔之后被执行,重复次数为repeat次,并且这个任务会在delay延时之后开始执行
node.schedule(callback, interval, repeat, delay);
// callback回调函数会在delay延时之后被执行一次
node.scheduleOnce(callback, delay);
// 取消callback任务
node.unschedule(callback);
// 取消node节点所有计划中的任务
node.unscheduleAllCallbacks();
|
本文来源:http://blog.csdn.net/et_sandy/article/details/40683921