const { ccclass, property } = cc._decorator; @ccclass export default class DaoJiShiProgress extends cc.Component { @property({ type: cc.Node, displayName: "进度条上面的人物", }) slider: cc.Node = null; @property({ type: cc.Node, displayName: "计时文字", }) timer: cc.Node = null; @property({ displayName: "总时间s", }) allTimeNum: number = 60; _dt: number = 0 isStartTimer: boolean = false//是否开始倒计时 curTimeNum: number = 0 progressWidth: number = 0 finishCallFunc = null //结束回调 callTarget = null //回调对象 start() { this.progressWidth = this.node.width; this.curTimeNum = this.allTimeNum; this.isStartTimer = false; this.updateProgress() } update(dt) { if (this.isStartTimer) { this.curTimeNum -= dt this.updateProgress() //倒计时结束 if (this.curTimeNum <= 0) { this.curTimeNum = 0 this.isStartTimer = false this.node.getComponent(cc.ProgressBar).progress = 0; this.timer.getComponent(cc.Label).string = "0"; this.slider.x = 0; this.finishCallFunc && (this.callTarget ? this.finishCallFunc.apply(this.callTarget) : this.finishCallFunc()); } } } //设置开始/结束倒计时 setIsStartTimer(bStart, finishCallFunc?: { target: any, callFunc: any }) { this.isStartTimer = bStart if (finishCallFunc) { this.finishCallFunc = finishCallFunc.callFunc; this.callTarget = finishCallFunc.target; } } //加时:秒 addTimer(time: number) { this.curTimeNum += time; this.allTimeNum += time; let rate = this.curTimeNum / this.allTimeNum; this.node.getComponent(cc.ProgressBar).progress = rate; this.timer.getComponent(cc.Label).string = Math.floor(this.curTimeNum).toString(); this.slider.x = rate * this.progressWidth; } updateProgress() { //未设置倒计时时间 if (this.allTimeNum <= 0) { return; } let rate = this.curTimeNum / this.allTimeNum; this.node.getComponent(cc.ProgressBar).progress = rate; this.timer.getComponent(cc.Label).string = Math.floor(this.curTimeNum).toString(); this.slider.x = rate * this.progressWidth; } }