Cocos Creator倒计时

需求:给定一个时间戳,计算剩余时间并进行倒计时

TypeScript 复制代码
    //更新截止时间
    private updateCountdownTime(timestamp) {

        const currentTime = Math.floor(Date.now() / 1000); //当前时间(秒)
        const targetTime = Math.floor(timestamp / 1000);// 给定时间戳(秒)
        // 时间换算,截止时间到当前时间
        const difference = targetTime - currentTime; // 时间差(秒)
        if (difference <= 0) {
            this.countdown.string = "已截止";
            return;
        }
        const days = Math.floor(difference / (3600 * 24)); // 截止天数 
        const hours = Math.floor((difference / 3600) % 24); //截止小时
        const minutes = Math.floor((difference / 60) % 60); // 截止分
        const remainingSeconds = difference % 60; //剩余秒

        const hStr = hours < 10 ? ('0' + hours) : hours;
        const mStr = minutes < 10 ? ('0' + minutes) : minutes;
        const sStr = remainingSeconds < 10 ? ('0' + remainingSeconds) : remainingSeconds;
        this.countdown.string = `${days}:${hStr}:${mStr}:${sStr}`;
    }

然后在Start中调用cocos的计时器方法即可。

TypeScript 复制代码
this.schedule(this.updateCountdownTime, 1, cc.macro.REPEAT_FOREVER, 1);

该方法原型如下:

(method) cc.Component.schedule(callback: Function, interval?: number, repeat?: number, delay?: number): void

调度一个自定义的回调函数。 如果回调函数已调度,那么将不会重复调度它,只会更新时间间隔参数。

具体内容可查看官方文档:

使用计时器 | Cocos Creator

相关推荐
陈言必行1 小时前
Unity 性能优化 之 编辑器创建资源优化( 工作流 | 场景 | 预制体)
unity·编辑器·游戏引擎
1uther7 小时前
Unity核心概念⑨:Screen
开发语言·游戏·unity·c#·游戏引擎
死也不注释10 小时前
【Unity UGUI 交互组件——Slider(7)】
unity·游戏引擎·交互
挂科是不可能出现的18 小时前
unity导入blender动画
unity·游戏引擎·blender
派葛穆19 小时前
Unity-按钮实现场景跳转
java·unity·游戏引擎
绀目澄清1 天前
unity UGUI 鼠标画线
unity·计算机外设·游戏引擎
Magnum Lehar1 天前
3d wpf游戏引擎的导入文件功能c++的.h实现
3d·游戏引擎·wpf
作孽就得先起床1 天前
unity pcd 二进制版 简单显示文件对象(单色)
unity·游戏引擎
陈言必行2 天前
Unity 性能优化 之 静态资源优化 (音频 | 模型 | 纹理 | 动画)
unity·性能优化·游戏引擎
Thomas_YXQ2 天前
Unity3D RectTransform.rect属性详解
unity·编辑器·游戏引擎·材质