using Godot;
namespace BITKit;
///
/// 固定间隔工具,用于控制执行速率
///
[System.Serializable]
public class IntervalTimer
{
public IntervalTimer()
{
}
///
/// 在构造函数中声明间隔时间
///
/// 间隔(秒)
public IntervalTimer(ulong interval)
{
this.interval = interval;
}
///
/// 间隔时间
///
private readonly ulong interval;
///
/// 可以执行的事件
///
private ulong allowTime;
///
/// 是否可以执行(执行重置间隔)
///
public bool Allow
{
get
{
if (allowTime >= Time.GetTicksMsec()) return false;
Release();
return true;
}
}
///
/// 是否可以执行(不会执行重置间隔)
///
public bool AllowWithoutRelease => allowTime >= Time.GetTicksMsec();
///
/// 重置执行间隔
///
/// 是否可以立即执行
public void Release(bool immediately=false)
{
var currentTime = Time.GetTicksMsec();
allowTime = immediately ? currentTime : currentTime + interval*1000;
}
}