在 cocos creator中,使用 Ts来实现如何时间开始计时

const { ccclass, property } = cc._decorator;

@ccclass
export default class TimeCounter extends cc.Component {

    @property(cc.Label)
    label: cc.Label = null;

    private elapsedTime: number = 0;
    private counting: boolean = false;

    start() {
        // 在开始时启动计时
        this.startTimer();
    }

    startTimer() {
        // 设置计时器为启动状态
        this.counting = true;

        // 使用schedule函数每秒执行一次updateTimer方法
        this.schedule(this.updateTimer, 1, cc.macro.REPEAT_FOREVER, 0);
    }

    updateTimer(dt: number) {
        // 如果计时器处于启动状态,更新已经流逝的时间
        if (this.counting) {
            this.elapsedTime += dt;
            // 在这里可以更新显示计时的文本
            this.label.string = this.formatTime(this.elapsedTime);
        }
    }

    stopTimer() {
        // 设置计时器为停止状态
        this.counting = false;
        // 取消schedule
        this.unschedule(this.updateTimer);
    }

    formatTime(seconds: number): string {
        // 将秒数格式化为分:秒的形式
        const minutes = Math.floor(seconds / 60);
        const remainingSeconds = Math.floor(seconds % 60);
        return `${minutes}:${remainingSeconds < 10 ? '0' : ''}${remainingSeconds}`;
    }
}

在预制体上挂载这个 label 对应 main 下挂载着一个脚本就可以实现了

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值