-
这个问题单机游戏可以不用处理,网络游戏中经常要显示倒计时,这个时间其实是服务器发过来一个总的时间,客户端这边启用一个倒计时来显示。
-
那么问题来了,客户端经常会出现倒计时还没跑完,服务器的那边已经跑完了,导致用户看到倒计时还没到0,游戏就莫名其妙的结束了
。
-
出现的原因主要有,1.客户端的卡顿到时倒计时不准,2.客户端切换后台导致。
-
常规的写法:定时器间隔时间1秒,总时间每次减1。
-
改进的写法:定时器间隔时间1秒,总时间每次不是单纯的减少1,而是在开始游戏的时候记住时间戳,每次是用当前的时间戳减去开始的时间戳得到真实的倒计时。
代码如下:
// 开始倒计时
startTimeCutDown(time){
let allTime = time;
let startOsTime = util.os.time();
this.timeNode.getComponent(cc.Label).string = allTime;
let scheduleCallback = function(){
let nowOsTime = util.os.time();
let nowTime = allTime - Math.floor((nowOsTime - startOsTime));
if(nowTime <= 0){
this.stopTimeCutDown();
}
this.timeNode.getComponent(cc.Label).string = nowTime;
}.bind(this);
this.timeNode.active = true;
this.sprShaoDeng.active = true;
this.timeNode.getComponent(cc.Label).schedule(scheduleCallback, 1);
},
// 停止倒计时
stopTimeCutDown(){
this.timeNode.getComponent(cc.Label).unscheduleAllCallbacks();
this.timeNode.active = false;
this.sprShaoDeng.active = false;
},