您的位置:首页 > 科技 > 能源 > Cocos Creator倒计时

Cocos Creator倒计时

2024/10/7 0:19:38 来源:https://blog.csdn.net/qq_62520130/article/details/141169047  浏览:    关键词:Cocos Creator倒计时

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

    //更新截止时间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的计时器方法即可。

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

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com