TimerMgr.ts 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. import { assetManager, instantiate, Prefab, Node, UITransform, Vec3, Vec2, view, game, director, Scheduler, Label } from "cc";
  2. import { GameUtil } from "../GameUtil";
  3. import { AliensGlobalInstance } from "../AliensGlobalInstance";
  4. /** 时间管理器*/
  5. export class TimerMgr {
  6. private static _instance: TimerMgr;
  7. public static get Instance(): TimerMgr {
  8. if (this._instance == null) {
  9. this._instance = new TimerMgr();
  10. }
  11. return this._instance;
  12. }
  13. public static get inst(): TimerMgr {
  14. return this.Instance;
  15. }
  16. public countDownTime: number = 1;
  17. private timerId: number = 0;
  18. private isPaused: boolean = false; // 添加暂停标志
  19. constructor() {
  20. }
  21. // 开始倒计时
  22. public startCountdown(): void {
  23. if (this.isPaused) {
  24. this.resumeCountdown();
  25. return;
  26. }
  27. this.upateLbTime();
  28. this.timerId = setInterval(() => {
  29. if (!this.isPaused) {
  30. this.countDownTime--;
  31. if (this.countDownTime <= 0) {
  32. this.stopCountdown();
  33. }
  34. this.upateLbTime();
  35. }
  36. }, 1000); // 每秒减少一次
  37. Scheduler.enableForTarget(this);
  38. director.getScheduler().schedule(this.update, this, 0);
  39. }
  40. private upateLbTime() {
  41. const battleUI = AliensGlobalInstance.instance.battleUI;
  42. const lbTime = battleUI.getChildByPath('Times/LbTime')!;
  43. // lbTime.getComponent(Label).string = this.countDownTime.toString();
  44. const format = GameUtil.formatToTimeString(this.countDownTime);
  45. lbTime.getComponent(Label).string = format;
  46. }
  47. // 停止倒计时
  48. private stopCountdown(): void {
  49. if (this.timerId) {
  50. clearInterval(this.timerId);
  51. this.timerId = 0;
  52. }
  53. }
  54. // 暂停倒计时
  55. public pauseCountdown(): void {
  56. this.isPaused = true;
  57. director.getScheduler().pauseTarget(this);
  58. }
  59. // 恢复倒计时
  60. public resumeCountdown(): void {
  61. this.isPaused = false;
  62. director.getScheduler().resumeTarget(this);
  63. }
  64. // 获取暂停状态
  65. public isPausedState(): boolean {
  66. return this.isPaused;
  67. }
  68. // update方法,每帧调用
  69. public update(dt: number): void {
  70. }
  71. // 销毁时清理
  72. public reset(): void {
  73. this.stopCountdown();
  74. this.isPaused = false; // 重置暂停状态
  75. Scheduler.enableForTarget(this);
  76. director.getScheduler().unscheduleAllForTarget(this);
  77. this.countDownTime = 10; //测试
  78. }
  79. }