cocos2d-js 定时器
2024-09-03 06:04:59
1.scheduleUpdate
节点中有scheduleUpdate接口,通过这个接口,可以让游戏在每帧执行都执行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({ // 监听鼠标事件
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类似,接受两个参数,第一个参数是回调函数,第二个参数是事件,scheduleOnce接受的时间以秒为单位。
节点都有scheduleOnce接口。
var ScheduleLayer = cc.Layer.extend({
ctor:function () {
this._super();
this.scheduleOnce(function () { // 2秒后打印日志
console.log("scheduleOnce");
},2);
}
})
3. schedule
schedule和setInterval类似,实现固定时间间隔不断触发某个函数的功能。
node.schedul(callback, interval, repeat, delay)
interval触发间隔,以秒为单位
repeat重复次数,会执行repeat+1次
delay是第一次出发前的延迟时间,以秒为单位
如果希望schedule无限循环,可以省略后两个参数,也可以设置repeat为常量cc.REPEATE_FOREVER
this.schedule(function () {
console.log("schedule");
},2,cc.REPEAT_FOREVER,2);
schedule基于帧数控制,当帧频降低时,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); //如果本次触发延迟了,就让下次触发早一点来抵消误差
callback.call(this);
}
}.bind(this),0); // 0表示每帧触发
}
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.暂停/恢复定时器
node.pause(); //暂停
node.resume(); //恢复
作者:写java的逗比叫z1
链接:http://www.jianshu.com/p/df26c8ef1671
最新文章
- mvc深入理解
- jQuery基础之(四)jQuery创建DOM元素
- imx6 otg host support
- 第三篇 SQL Server代理警报和操作员
- RedMine项目管理系统邮件推送设置(Windows环境)
- 11 java 反射机制
- redis安装linux(二)
- 项目设计day1
- linux 软件包管理介绍
- linux 分区方案
- ios集成极光推送:Undefined symbols for architecture arm64: ";_dns_parse_resource_record";, referenced from:?
- 【HNOI 2018】排列
- mysql按天,按周,按月,按季度,按年统计数据
- Maven install报MojoExecutionException
- 【算法python实现】 -- 不同路径
- ASCII码与16进制的互相转换(表)
- 在虚拟机中使用Ghost系统盘安装
- 修改Linux内核参数,减少TCP连接中的TIME-WAIT
- java—将查询的结果封装成List<;Map>;与用回调函数实现数据的动态封装(44)
- 手动封装一个属于自己的AJAX类库