| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374 |
- import { Component, EventHandler, Label, _decorator } from "cc";
- import { BitmapFont } from "./BitmapFont";
- const { ccclass, property } = _decorator;
- /**
- * 倒计时组件
- * @author 袁浩
- */
- @ccclass("CountDown")
- export class CountDown extends Component {
- @property({ tooltip: "倒计时总时间(秒)", min: 0, step: 1 })
- public value: number = 30;
- @property({ tooltip: "倒计时刷新间隔(秒)", min: 0, step: 1 })
- public interval: number = 1;
- @property({ tooltip: "倒计时进度值小数点个数", min: 0, step: 1 })
- public fractionDigits: number = 0;
- @property({ tooltip: "用于显示倒计时的文本", type: Label })
- public label: Label;
- @property({ tooltip: "用于显示倒计时的位图文本", type: BitmapFont })
- public bitmapFont: BitmapFont;
- @property({ tooltip: "进度是否反转计算,如果设为true,则会从0开始刷新到总时间" })
- public reverse: boolean = false;
- @property({ tooltip: "是否在倒计时组件运行时自动播放倒计时" })
- public playOnLoad: boolean = true;
- @property({ tooltip: "间隔回调", type: EventHandler })
- public onInterval: EventHandler;
- @property({ tooltip: "完成回调", type: EventHandler })
- public onComplete: EventHandler;
- private progressOriginal: number = 0;
- private lastInterval: number = 0;
- /**
- * 倒计时进度
- */
- public get progress(): number {
- var p = Number(this.progressOriginal.toFixed(this.fractionDigits));
- return this.reverse ? p : this.value - p;
- }
- private _running: boolean = false;
- /**
- * 倒计时是否正在运行
- */
- public get running(): boolean {
- return this._running;
- }
- onLoad() {
- this.playOnLoad && (this._running = true);
- }
- /**
- * 开始播放倒计时,如果倒计时正在运行则无效
- */
- public play() {
- if (!this._running) {
- this.progressOriginal = this.lastInterval = 0;
- this._running = true;
- }
- }
- public stop() {
- this._running = false;
- }
- update(delta: number) {
- if (this._running) {
- this.label && (this.label.string = this.progress + "");
- this.bitmapFont && (this.bitmapFont.string = this.progress + "");
- this.progressOriginal += delta;
- while (this.progressOriginal - this.lastInterval >= this.interval) {//如果到了计算刷新间隔的时间
- this.lastInterval += this.interval;
- this.onInterval && this.onInterval.emit([this.progress]);
- }
- if (this.progressOriginal >= this.value) {
- this.onComplete && this.onComplete.emit([]);
- this._running = false;
- }
- }
- }
- }
|