/** * 计时器管理类 * @description * @author 冯聪 */ export default class TimerSystem extends cc.Component { /** 计数器数组 */ private timerArr: Timer[] = []; /** 开启游戏计时器 */ public startTimer() { this.schedule(() => { this.runTimer(); }, 1); } /** 运行游戏计时器 */ private runTimer() { for (var i: number = 0; i < this.timerArr.length; i++) { var gameTimer: Timer = this.timerArr[i]; var callBack: Function = gameTimer.callBack; var target: any = gameTimer.target; gameTimer.curTime--; if (gameTimer.curTime <= 0) { gameTimer.curTime = gameTimer.totalTime; callBack.call(target); } } } /** * 添加游戏计时器 * @description * @param time 计时的时间 * @param callBack 计时结束之后的回调 * @param target 计时绑定的脚本对象 */ public addTimer(time: number, callBack: Function, target: any) { if (!this.ifHasSameTimer(callBack, target)) { let gameTimer = new Timer(); gameTimer.curTime = time; gameTimer.totalTime = time; gameTimer.callBack = callBack; gameTimer.target = target; this.timerArr.push(gameTimer); } } /** * 是否有相同的时间管理器 * @param callBack 回调方法 * @param target 绑定的对象 */ private ifHasSameTimer(callBack: Function, target: any): boolean { if (this.getTimer(callBack, target)) { //重复添加时间计时器 return true; } else { return false; } } /** * 获取时间管理器 * @param callBack 回调方法 * @param target 绑定的对象 */ private getTimer(callBack: Function, target: any): Timer { for (var i: number = this.timerArr.length - 1; i >= 0; i--) { let gameTimer: Timer = this.timerArr[i]; if (gameTimer.callBack == callBack && gameTimer.target == target) { return gameTimer; } } return null; } /** * 移除时间管理器 * @param callBack 回调方法 * @param target 绑定的对象 */ public removeTimer(callBack: Function, target: any) { for (var i: number = this.timerArr.length - 1; i >= 0; i--) { let timer: Timer = this.timerArr[i]; if (timer.callBack == callBack && timer.target == target) { this.timerArr.splice(i, 1) //gameTimer = null; //要不要加null 看最后的效果 return; } } } } /** 游戏计时器类 */ export class Timer { /** 当前计时时间 */ curTime: number = 0; /** 计时总时间 */ totalTime: number = 0; /** 计时的回调 */ callBack: Function = null; /** 绑定的脚本对象 */ target: any = null; }