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

相关推荐
jtymyxmz1 天前
《Unity Shader》10.1.4 折射
unity·游戏引擎
熬夜敲代码的小N2 天前
Unity WebRequest高级操作:构建高效稳定的网络通信模块
android·数据结构·unity·游戏引擎
萘柰奈2 天前
Unity【小问题】----URP项目中加载AssetBundle中的预设体即使加载了依赖的材质依然是紫色的问题
unity·游戏引擎·材质
海中有金2 天前
Unreal Engine 线程模型深度解析[2]
人工智能·游戏引擎·虚幻
海中有金2 天前
Unreal Engine 内存池浅谈[11]——总结篇
游戏引擎·虚幻
熊猫悟道2 天前
Unity shader 之,Shader内部时间离散处理
unity·游戏引擎·材质·着色器
PA_3 天前
unity Component-Based Architecture游戏框架
游戏·unity·游戏引擎
jtymyxmz3 天前
《Unity Shader》11.3.2 广告牌技术
unity·游戏引擎
jtymyxmz3 天前
《Unity Shader》11.3.1 流动的河流
unity·游戏引擎
小马过河R3 天前
开发游戏需要哪些岗位和角色参与
游戏·游戏引擎·游戏程序