Created
March 12, 2019 12:04
-
-
Save RevenantX/e821b837944076db6ead25b16a4a9f26 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Diagnostics; | |
namespace Game.Shared.Helpers | |
{ | |
public class LogicTimer | |
{ | |
public const float FixedDelta = 0.015f; | |
public const long FixedDeltaNano = 15000 * 1000L; | |
public const float TicksPerSecond = 1.0f / FixedDelta; | |
public const long NanoSecond = 1000000000L; | |
private long _statsAccumulator; | |
private int _ticks; | |
private long _accumulator; | |
private long _lastTime; | |
private readonly Stopwatch _stopwatch; | |
private readonly Action _action; | |
private readonly Action _secondAction; | |
public long StatsTimer | |
{ | |
get { return _statsAccumulator; } | |
} | |
public int Ticks | |
{ | |
get { return _ticks; } | |
} | |
public float LerpAlpha | |
{ | |
get | |
{ | |
return (_accumulator / (float)FixedDeltaNano); | |
} | |
} | |
public LogicTimer(Action action, Action secondAction) | |
{ | |
_stopwatch = new Stopwatch(); | |
_action = action; | |
_secondAction = secondAction; | |
} | |
public LogicTimer(Action action) | |
{ | |
_stopwatch = new Stopwatch(); | |
_action = action; | |
} | |
public void Start() | |
{ | |
_stopwatch.Start(); | |
} | |
public void Stop() | |
{ | |
_stopwatch.Stop(); | |
} | |
public bool Update() | |
{ | |
bool ticked = false; | |
long elapsedTicks = _stopwatch.ElapsedTicks; | |
long delta = ((elapsedTicks - _lastTime)*NanoSecond)/Stopwatch.Frequency; | |
_accumulator += delta; | |
_statsAccumulator += delta; | |
_lastTime = elapsedTicks; | |
while (_accumulator >= FixedDeltaNano) | |
{ | |
_action(); | |
_accumulator -= FixedDeltaNano; | |
_ticks++; | |
ticked = true; | |
} | |
if (_statsAccumulator >= NanoSecond) | |
{ | |
if (_secondAction != null) | |
{ | |
_secondAction(); | |
} | |
_accumulator += _statsAccumulator - NanoSecond; | |
_statsAccumulator -= NanoSecond; | |
_ticks = 0; | |
_lastTime = 0; | |
_stopwatch.Reset(); | |
_stopwatch.Start(); | |
} | |
return ticked; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment