倒计时(CocosCreator)

推荐阅读:

  •  我的CSDN
  •  我的博客园
  •  QQ群:704621321

      在游戏中,还有一个经常使用的功能就是倒计时。比如:距离活动开奖时间;当前活动的剩余时间等,都会用到倒计时,下面给大家讲讲根据当服务器发送的数据,实现倒计时功能。

1.服务器发送剩余时间戳(毫秒)

    countdown(remainTime,txt) {
        var self = this;
        let time = parseInt(remainTime/ 1000);
        var call1 = app.callFunc(function (adt) {
            time = time - 1;
            txt.string = self.formatTime(Math.max(0, time));
            if (time <= 0) {
                txt.node.stopAllActions();
            }
        }, txt.node);
        var delay = cc.delayTime(1);
        txt.node.runAction(cc.repeatForever(cc.sequence(call1, delay)));
    },
    /// 计算时间格式
    formatTime(t) {
        var h = Math.floor(t / 3600);
        var m = Math.floor(t % 3600 / 60);
        var s = Math.floor(t % 3600 % 60);
        return "{0}{1}{2}".format(h > 0 ? (this.addZero(h) + ":") : "00:",this.addZero(m) + ":") : "00:", s > 0 ? (this.addZero(s) + "") : "00");
    },

2.服务器发送开始,结束时间戳(毫秒)

    countdown(end,txt) {
        var self = this;
        txt.node.stopAllActions();
        var timestamp = Date.parse(new Date());//获取当前时间戳
        let time = parseInt((end - timestamp) / 1000);
        var call1 = app.callFunc(function (adt) {
            time = time - 1;
            txt.string = self.formatTime(Math.max(0, time));
            if (time <= 0) {
                txt.node.stopAllActions();
            }
        }, txt.node);
        var delay = cc.delayTime(1);
        txt.node.runAction(cc.repeatForever(cc.sequence(call1, delay)));
    },
    /// 计算时间格式
    formatTime(t) {
        var h = Math.floor(t / 3600);
        var m = Math.floor(t % 3600 / 60);
        var s = Math.floor(t % 3600 % 60);
        return "{0}{1}{2}".format(h > 0 ? (this.addZero(h) + ":") : "00:",this.addZero(m) + ":") : "00:", s > 0 ? (this.addZero(s) + "") : "00");
    },

3.总结

      比较上面两种情况,大致思想都是一样的,都用用的剩余时间戳计算倒计时的,在函数formatTime中,用于将秒为单位的时间转换为00:00:00的形式。唯一不同的是情况(1)中剩余时间戳是已知的;情况二中需要用:结束时间—戳当前时间戳=剩余时间戳。

你可能感兴趣的:(CocosCreator)