TimerSystem.ts 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  1. /**
  2. * 计时器管理类
  3. * @description
  4. * @author 冯聪
  5. */
  6. export default class TimerSystem extends cc.Component {
  7. /** 计数器数组 */
  8. private timerArr: Timer[] = [];
  9. /** 开启游戏计时器 */
  10. public startTimer() {
  11. this.schedule(() => {
  12. this.runTimer();
  13. }, 1);
  14. }
  15. /** 运行游戏计时器 */
  16. private runTimer() {
  17. for (var i: number = 0; i < this.timerArr.length; i++) {
  18. var gameTimer: Timer = this.timerArr[i];
  19. var callBack: Function = gameTimer.callBack;
  20. var target: any = gameTimer.target;
  21. gameTimer.curTime--;
  22. if (gameTimer.curTime <= 0) {
  23. gameTimer.curTime = gameTimer.totalTime;
  24. callBack.call(target);
  25. }
  26. }
  27. }
  28. /**
  29. * 添加游戏计时器
  30. * @description
  31. * @param time 计时的时间
  32. * @param callBack 计时结束之后的回调
  33. * @param target 计时绑定的脚本对象
  34. */
  35. public addTimer(time: number, callBack: Function, target: any) {
  36. if (!this.ifHasSameTimer(callBack, target)) {
  37. let gameTimer = new Timer();
  38. gameTimer.curTime = time;
  39. gameTimer.totalTime = time;
  40. gameTimer.callBack = callBack;
  41. gameTimer.target = target;
  42. this.timerArr.push(gameTimer);
  43. }
  44. }
  45. /**
  46. * 是否有相同的时间管理器
  47. * @param callBack 回调方法
  48. * @param target 绑定的对象
  49. */
  50. private ifHasSameTimer(callBack: Function, target: any): boolean {
  51. if (this.getTimer(callBack, target)) {
  52. //重复添加时间计时器
  53. return true;
  54. }
  55. else {
  56. return false;
  57. }
  58. }
  59. /**
  60. * 获取时间管理器
  61. * @param callBack 回调方法
  62. * @param target 绑定的对象
  63. */
  64. private getTimer(callBack: Function, target: any): Timer {
  65. for (var i: number = this.timerArr.length - 1; i >= 0; i--) {
  66. let gameTimer: Timer = this.timerArr[i];
  67. if (gameTimer.callBack == callBack && gameTimer.target == target) {
  68. return gameTimer;
  69. }
  70. }
  71. return null;
  72. }
  73. /**
  74. * 移除时间管理器
  75. * @param callBack 回调方法
  76. * @param target 绑定的对象
  77. */
  78. public removeTimer(callBack: Function, target: any) {
  79. for (var i: number = this.timerArr.length - 1; i >= 0; i--) {
  80. let timer: Timer = this.timerArr[i];
  81. if (timer.callBack == callBack && timer.target == target) {
  82. this.timerArr.splice(i, 1)
  83. //gameTimer = null; //要不要加null 看最后的效果
  84. return;
  85. }
  86. }
  87. }
  88. }
  89. /** 游戏计时器类 */
  90. export class Timer {
  91. /** 当前计时时间 */
  92. curTime: number = 0;
  93. /** 计时总时间 */
  94. totalTime: number = 0;
  95. /** 计时的回调 */
  96. callBack: Function = null;
  97. /** 绑定的脚本对象 */
  98. target: any = null;
  99. }