您的位置:首页 > 移动开发 > Cocos引擎

cocos-2d-js 定时器模板

2016-07-10 18:50 447 查看
var USER_TIME_COUNT_SET_TIME = "USER_TIME_COUNT_SET_TIME"   //设置倒计时时间
var USER_TIME_COUNT_START = "USER_TIME_COUNT_START"         //开始倒计时
var USER_TIME_COUNT_PAUSE = "USER_TIME_COUNT_PAUSE"           //停止倒计时
var USER_TIME_COUNT_FINISH = "USER_TIME_COUNT_FINISH"       //倒计时结束     由定时器抛出
var TimeCount = cc.Layer.extend({
EventArr:[USER_TIME_COUNT_SET_TIME, USER_TIME_COUNT_START, USER_TIME_COUNT_PAUSE],
Label_time:null,
Label_Position:null,
Count_Time:0,
ScheduleRun:false,
Start_DateTime:0,
ctor:function(){
this._super()
this.init()
},
init:function(){
this.Label_Position = cc.p(cc.winSize.width>>1,cc.winSize.height*0.95);       //调整倒计时坐标
this.Label_time = new cc.LabelBMFont("TimeCount", "res/mikado_outline_shadow.fnt");
if(this.Label_time.width <= 0)
this.Label_time.setPosition(this.Label_Position)
this.addChild(this.Label_time)
this.scheduleUpdate()

for(var index in this.EventArr){
var event = this.EventArr[index]
cc.eventManager.addCustomListener(event, this.onGetCustom.bind(this))
}
},
onGetCustom:function(event){
var data = event.getUserData();
switch (event.getEventName()){
case USER_TIME_COUNT_SET_TIME:
cc.log('设置了倒计时时间:',data)
this.Count_Time = data
this.Label_time.setString(this.Count_Time)
break
            case USER_TIME_COUNT_START:
cc.log('启动了倒计时:')
this.Start_DateTime = Date.now()
this.ScheduleRun = true
                break
            case USER_TIME_COUNT_PAUSE:
cc.log('停止了倒计时')
this.ScheduleRun = false
                break
}
},
update:function(){
if(this.ScheduleRun){
if(Date.now() - this.Start_DateTime>=1000){
this.Count_Time --;
this.Label_time.setString(this.Count_Time)
this.Start_DateTime += 1000
if(0 == this.Count_Time){
this.timeStop()
cc.eventManager.dispatchCustomEvent(USER_TIME_COUNT_FINISH)
}
}
}
},
timeStop:function(){
cc.log('倒计时结束了:')
this.ScheduleRun = false
},
onExit:function(){
this.unscheduleUpdate()
this.removeAllChildren(true)
for(var index in this.EventArr){
var event = this.EventArr[index]
cc.eventManager.removeCustomListeners(event)
}
}
})


onEnterTransitionDidFinish:function(){
this._super()
var that = this
cc.eventManager.dispatchCustomEvent(USER_TIME_COUNT_SET_TIME, 5)
cc.eventManager.dispatchCustomEvent(USER_TIME_COUNT_START)
cc.eventManager.addCustomListener(USER_TIME_COUNT_FINISH, function(event){
cc.log('app 获取了定时器传回的结束')})
},

onEnter()   是在进入场景的一瞬间就开始执行了。onEnterTransitionDidFinish() 是在完全进入场景后开始执行的。
                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: