BITKit/Src/Core/Ticker/TimerTicker.cs

72 lines
1.6 KiB
C#

using System;
using BITKit;
using Timer = System.Timers.Timer;
namespace BITKit
{
public class TimerTicker:ITicker
{
public TimerTicker()
{
_timer = new Timer();
_timer.Elapsed += (sender, args) =>
{
OnTick();
if (_timer.Enabled && _timer.AutoReset is false)
{
_timer.Start();
}
};
}
public int TickRate { get; set; }
public ulong TickCount { get; private set; }
private readonly Timer _timer;
private float _deltaTime;
private event Action<float> Tick;
public void Add(Action action)
{
throw new NotImplementedException();
}
public void Add(Action<float> action)
{
Tick += action;
}
public void Remove(Action<float> action)
{
Tick -= action;
}
public void ManualTick(float delta)
{
throw new NotImplementedException();
}
public TimerTicker Start()
{
_deltaTime = 1f / TickRate;
_timer.Interval = TimeSpan.FromSeconds(_deltaTime).TotalMilliseconds;
_timer.Enabled = true;
return this;
}
private void OnTick()
{
try
{
TickCount++;
Tick?.Invoke(_deltaTime);
}
catch (Exception e)
{
BIT4Log.LogException(e);
}
}
public void Stop()
{
_timer.Enabled = false;
}
}
}