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

相关推荐
胜天半子_王二_王半仙2 小时前
godot源码编译
游戏引擎·godot
Tandy12356_3 小时前
Godot开发2D冒险游戏——第二节:主角光环整起来!
游戏引擎·godot
星火撩猿11 小时前
常见游戏引擎介绍与对比
unity·ue5·游戏引擎·godot
sky_smile_Allen12 小时前
[Unity]-[UI]-[Prefab] 关于Unity UGUI 的布局及组件讲解
ui·unity·游戏引擎
虾球xz14 小时前
游戏引擎学习第244天: 完成异步纹理下载
c++·学习·游戏引擎
Magnum Lehar20 小时前
ApophisZerg游戏引擎项目目录展示
人工智能·vscode·编辑器·游戏引擎
Tandy12356_1 天前
Godot开发2D冒险游戏——第一节:主角登场!
python·游戏引擎·godot
是阿根1 天前
unity使用iTextSharp生成PDF文件
unity·c#·游戏引擎
常城2 天前
Unity中通过TMP使用图片字体
unity·游戏引擎
惊鸿醉2 天前
⭐Unity 开发 | 如何通过 NTP 网络时间实现精准的跨平台时间同步【附完整源码 + UI 模块 + 偏差分析】
网络·unity·游戏引擎