CountDown.ts 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. import { Component, EventHandler, Label, _decorator } from "cc";
  2. import { BitmapFont } from "./BitmapFont";
  3. const { ccclass, property } = _decorator;
  4. /**
  5. * 倒计时组件
  6. * @author 袁浩
  7. */
  8. @ccclass("CountDown")
  9. export class CountDown extends Component {
  10. @property({ tooltip: "倒计时总时间(秒)", min: 0, step: 1 })
  11. public value: number = 30;
  12. @property({ tooltip: "倒计时刷新间隔(秒)", min: 0, step: 1 })
  13. public interval: number = 1;
  14. @property({ tooltip: "倒计时进度值小数点个数", min: 0, step: 1 })
  15. public fractionDigits: number = 0;
  16. @property({ tooltip: "用于显示倒计时的文本", type: Label })
  17. public label: Label;
  18. @property({ tooltip: "用于显示倒计时的位图文本", type: BitmapFont })
  19. public bitmapFont: BitmapFont;
  20. @property({ tooltip: "进度是否反转计算,如果设为true,则会从0开始刷新到总时间" })
  21. public reverse: boolean = false;
  22. @property({ tooltip: "是否在倒计时组件运行时自动播放倒计时" })
  23. public playOnLoad: boolean = true;
  24. @property({ tooltip: "间隔回调", type: EventHandler })
  25. public onInterval: EventHandler;
  26. @property({ tooltip: "完成回调", type: EventHandler })
  27. public onComplete: EventHandler;
  28. private progressOriginal: number = 0;
  29. private lastInterval: number = 0;
  30. /**
  31. * 倒计时进度
  32. */
  33. public get progress(): number {
  34. var p = Number(this.progressOriginal.toFixed(this.fractionDigits));
  35. return this.reverse ? p : this.value - p;
  36. }
  37. private _running: boolean = false;
  38. /**
  39. * 倒计时是否正在运行
  40. */
  41. public get running(): boolean {
  42. return this._running;
  43. }
  44. onLoad() {
  45. this.playOnLoad && (this._running = true);
  46. }
  47. /**
  48. * 开始播放倒计时,如果倒计时正在运行则无效
  49. */
  50. public play() {
  51. if (!this._running) {
  52. this.progressOriginal = this.lastInterval = 0;
  53. this._running = true;
  54. }
  55. }
  56. public stop() {
  57. this._running = false;
  58. }
  59. update(delta: number) {
  60. if (this._running) {
  61. this.label && (this.label.string = this.progress + "");
  62. this.bitmapFont && (this.bitmapFont.string = this.progress + "");
  63. this.progressOriginal += delta;
  64. while (this.progressOriginal - this.lastInterval >= this.interval) {//如果到了计算刷新间隔的时间
  65. this.lastInterval += this.interval;
  66. this.onInterval && this.onInterval.emit([this.progress]);
  67. }
  68. if (this.progressOriginal >= this.value) {
  69. this.onComplete && this.onComplete.emit([]);
  70. this._running = false;
  71. }
  72. }
  73. }
  74. }