分享web开发知识

注册/登录|最近发布|今日推荐

主页 IT知识网页技术软件开发前端开发代码编程运营维护技术分享教程案例
当前位置:首页 > 前端开发

cocos2d-js 定时器

发布时间:2023-09-06 01:18责任编辑:傅花花关键词:js定时器

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

cocos2d-js 定时器

原文地址:http://www.cnblogs.com/kefeiGame/p/7681023.html

知识推荐

我的编程学习网——分享web前端后端开发技术知识。 垃圾信息处理邮箱 tousu563@163.com 网站地图
icp备案号 闽ICP备2023006418号-8 不良信息举报平台 互联网安全管理备案 Copyright 2023 www.wodecom.cn All Rights Reserved