using System; using System.Runtime.InteropServices.WindowsRuntime; using UnityEngine; namespace Core.Utilities { /// /// A timer data model. Consumed/process by the TimedBehaviour /// 塔防游戏的基础Timer包装类,设置一个time时间后要引发的操作,然后每一轮Tick这个Timer,触发后Tick返回true /// 由调用层进行相应的操作。 /// public class Timer { /// /// Event fired on elapsing /// readonly Action m_Callback; /// /// The time /// float m_Time, m_CurrentTime; protected static int TIMER_IDSTART = 0; protected int mTimerID = 0; /// /// Normalized progress of the timer /// public float normalizedProgress { get { return Mathf.Clamp(m_CurrentTime / m_Time, 0f, 1f); } } public float currentTime { get { return this.m_CurrentTime; } } public int timerID { get { return this.mTimerID; } } /// /// Timer constructor /// /// the time that timer is counting /// the event fired at the end of the timer elapsing public Timer(float newTime, Action onElapsed = null) { SetTime(newTime); m_CurrentTime = 0f; m_Callback += onElapsed; mTimerID = TIMER_IDSTART++; } /// /// Returns the result of AssessTime /// /// change in time between ticks /// true if the timer has elapsed, false otherwise public virtual bool Tick(float deltaTime) { return AssessTime(deltaTime); } /// /// Checks if the time has elapsed and fires the tick event /// /// the change in time between assessments /// true if the timer has elapsed, false otherwise protected bool AssessTime(float deltaTime) { m_CurrentTime += deltaTime; if (m_CurrentTime >= m_Time) { FireEvent(); return true; } return false; } /// /// Resets the current time to 0 /// public void Reset() { m_CurrentTime = 0; } /// /// Fires the associated timer event /// public void FireEvent() { m_Callback.Invoke(); } /// /// Sets the elapsed time /// /// sets the time to a new value public void SetTime(float newTime) { m_Time = newTime; if (newTime <= 0) { m_Time = 0.1f; } } } }