1.scheduleUpdate
節(jié)點中有scheduleUpdate接口,通過這個接口,可以讓游戲在每幀執(zhí)行都執(zhí)行update方法
var ScheduleUpdateLayer = cc.Layer.extend({
ball:null,
ctor:function () {
this._super();
this.scheduleUpdate(); // 開啟定時器
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)聽鼠標事件
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類似,接受兩個參數(shù),第一個參數(shù)是回調(diào)函數(shù),第二個參數(shù)是事件,scheduleOnce接受的時間以秒為單位。
節(jié)點都有scheduleOnce接口。
var ScheduleLayer = cc.Layer.extend({
ctor:function () {
this._super();
this.scheduleOnce(function () { // 2秒后打印日志
console.log("scheduleOnce");
},2);
}
})
3. schedule
schedule和setInterval類似,實現(xiàn)固定時間間隔不斷觸發(fā)某個函數(shù)的功能。
node.schedul(callback, interval, repeat, delay)
interval觸發(fā)間隔,以秒為單位
repeat重復(fù)次數(shù),會執(zhí)行repeat+1次
delay是第一次出發(fā)前的延遲時間,以秒為單位
如果希望schedule無限循環(huán),可以省略后兩個參數(shù),也可以設(shè)置repeat為常量cc.REPEATE_FOREVER
this.schedule(function () {
console.log("schedule");
},2,cc.REPEAT_FOREVER,2);
schedule基于幀數(shù)控制,當幀頻降低時,schedule會積累大量的誤差
一個平衡的定時器
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ā)早一點來抵消誤差
callback.call(this);
}
}.bind(this),0); // 0表示每幀觸發(fā)
}
4. 取消定時器
- 取消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ù)定時器
node.pause(); //暫停
node.resume(); //恢復(fù)
參考資料 Cocos2d-JS開發(fā)之旅 鄭高強著 電子工業(yè)出版社