1.scheduleUpdate
節(jié)點(diǎn)中有scheduleUpdate接口,通過(guò)這個(gè)接口,可以讓游戲在每幀執(zhí)行都執(zhí)行update方法
var ScheduleUpdateLayer = cc.Layer.extend({
ball:null,
ctor:function () {
this._super();
this.scheduleUpdate(); // 開(kāi)啟定時(shí)器
var winSize = cc.director.getWinSize();
var ball = new cc.Sprite("res/item_2.png");
ball.x = winSize.width/2;
ball.y = winSize.height/2;
this.addChild(ball);
this.ball = ball;
cc.eventManager.addListener({ // 監(jiān)聽(tīng)鼠標(biāo)事件
event:cc.EventListener.MOUSE,
onMouseDown:function (event) {
var action = cc.moveTo(1,event.getLocation().x,event.getLocation().y);
ball.runAction(action);
}
},this)
},
update : function () { // 重寫update方法
console.log(this.ball.x+"---"+this.ball.y);
}
})
2. scheduleOnce
scheduleOnce和setTimeout類似,接受兩個(gè)參數(shù),第一個(gè)參數(shù)是回調(diào)函數(shù),第二個(gè)參數(shù)是事件,scheduleOnce接受的時(shí)間以秒為單位。
節(jié)點(diǎn)都有scheduleOnce接口。
var ScheduleLayer = cc.Layer.extend({
ctor:function () {
this._super();
this.scheduleOnce(function () { // 2秒后打印日志
console.log("scheduleOnce");
},2);
}
})
3. schedule
schedule和setInterval類似,實(shí)現(xiàn)固定時(shí)間間隔不斷觸發(fā)某個(gè)函數(shù)的功能。
node.schedul(callback, interval, repeat, delay)
interval觸發(fā)間隔,以秒為單位
repeat重復(fù)次數(shù),會(huì)執(zhí)行repeat+1次
delay是第一次出發(fā)前的延遲時(shí)間,以秒為單位
如果希望schedule無(wú)限循環(huán),可以省略后兩個(gè)參數(shù),也可以設(shè)置repeat為常量cc.REPEATE_FOREVER
this.schedule(function () {
console.log("schedule");
},2,cc.REPEAT_FOREVER,2);
schedule基于幀數(shù)控制,當(dāng)幀頻降低時(shí),schedule會(huì)積累大量的誤差
一個(gè)平衡的定時(shí)器
schedule2:function (callback,interval) {
var then = Date.now();
interval = interval*1000;
this.schedule(function () {
var now = Date.now();
var delta = now-then;
if(delta > interval){
then = now - (delta % interval); //如果本次觸發(fā)延遲了,就讓下次觸發(fā)早一點(diǎn)來(lái)抵消誤差
callback.call(this);
}
}.bind(this),0); // 0表示每幀觸發(fā)
}
4. 取消定時(shí)器
- 取消scheduleUpdate ,使用 node.unscheduleUpdate()
- 取消scheduleOnce和schedule,使用node.unschedule()
var ScheduleLayer = cc.Layer.extend({
ctor:function () {
this._super();
this.schedule(this.tick,1,cc.REPEAT_FOREVER,1);
this.tickCount = 0;
},
tick:function () {
console.log("tick");
this.tickCount++;
if(this.tickCount == 5){
this.unschedule(this.tick);
}
}
})
5.暫停/恢復(fù)定時(shí)器
node.pause(); //暫停
node.resume(); //恢復(fù)
參考資料 Cocos2d-JS開(kāi)發(fā)之旅 鄭高強(qiáng)著 電子工業(yè)出版社