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

相关推荐
AA陈超1 天前
虚幻引擎5 GAS开发俯视角RPG游戏 P07-11 实现自动运行
c++·游戏·ue5·游戏引擎·虚幻
Hody912 天前
【XR开发系列】Unity下载与安装详细教程(UnityHub、Unity)
unity·游戏引擎·xr
雪下的新火3 天前
Blender-一个简单的水
游戏引擎·blender·特效制作·笔记分享
weixin_424294673 天前
在 Unity 游戏开发中,为视频选择 VP8 还是 H.264
unity·游戏引擎
一步一个foot-print4 天前
【Unity】Light Probe 替代点光源给环境动态物体加光照
unity·游戏引擎
@LYZY4 天前
Unity 中隐藏文件规则
unity·游戏引擎·游戏程序·vr
Sator14 天前
使用Unity ASE插件设置数值不会生效的问题
unity·游戏引擎
AA陈超4 天前
虚幻引擎5 GAS开发俯视角RPG游戏 P07-08 点击移动
c++·游戏·ue5·游戏引擎·虚幻
程序猿追5 天前
轻量级云原生体验:在OpenEuler 25.09上快速部署单节点K3s
人工智能·科技·机器学习·unity·游戏引擎
B0URNE5 天前
【Unity基础详解】(7)Unity核心:动画系统
unity·游戏引擎