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

相关推荐
淡海水7 小时前
【节点】[Houndstooth节点]原理解析与实际应用
unity·游戏引擎·shadergraph·图形·houndstooth
DoomGT1 天前
Physics Simulation - Hit Event的触发机制
ue5·游戏引擎·虚幻·虚幻引擎·unreal engine
jtymyxmz1 天前
《Unity Shader》14.1 卡通风格的渲染
unity·游戏引擎
Howrun7772 天前
虚幻引擎_核心框架
游戏引擎·虚幻
GLDbalala2 天前
Unity 实现一个简单的构建机
unity·游戏引擎
JIes__3 天前
Unity(二)——Resources资源动态加载
unity·游戏引擎
地狱为王3 天前
Unity使用NovaSR将沉闷的16kHz音频升频成清晰的48kHz音频
unity·游戏引擎·音视频·novasr
孟无岐4 天前
【Laya】Socket 使用指南
websocket·typescript·游戏引擎·游戏程序·laya
tealcwu4 天前
【Unity资源】Unity MCP 介绍
unity·游戏引擎
晚霞的不甘4 天前
Flutter for OpenHarmony 引力弹球游戏开发全解析:从零构建一个交互式物理小游戏
前端·flutter·云原生·前端框架·游戏引擎·harmonyos·骨骼绑定