Skip to content

Instantly share code, notes, and snippets.

@CptAsgard
Last active May 18, 2022 18:02
Show Gist options
  • Save CptAsgard/bb7f760cd630f595eee3f37d1e96c2d2 to your computer and use it in GitHub Desktop.
Save CptAsgard/bb7f760cd630f595eee3f37d1e96c2d2 to your computer and use it in GitHub Desktop.
DarkRift 2 / .NET 6 - fixed update tick/loop for standalone plugin
public class GameTime
{
private readonly Stopwatch stopwatch = new();
public const float TicksPerSecond = 4f;
public float FixedDeltaTime => 1f / TicksPerSecond;
public long FixedDeltaTimeMiliseconds => (long)(FixedDeltaTime * 1000f);
public long ElapsedMiliseconds => stopwatch.ElapsedMilliseconds;
public long ElapsedTimeSeconds => stopwatch.ElapsedMilliseconds / 1000L;
public GameTime()
{
stopwatch.Start();
}
}
private readonly Thread thread;
private readonly CancellationToken token;
private readonly GameTime gameTime = new();
private long previousElapsedMiliseconds = 0;
private long combinedDeltaTime = 0;
public WorldManager(PluginLoadData pluginLoadData) : base(pluginLoadData)
{
thread = new(RunLoop);
thread.Start();
}
private void RunLoop()
{
previousElapsedMiliseconds = gameTime.ElapsedMiliseconds;
while (!token.IsCancellationRequested)
{
long elapsed = gameTime.ElapsedMiliseconds;
long deltaTime = elapsed - previousElapsedMiliseconds;
previousElapsedMiliseconds = elapsed;
combinedDeltaTime += deltaTime;
while (combinedDeltaTime >= gameTime.FixedDeltaTimeMiliseconds)
{
combinedDeltaTime -= gameTime.FixedDeltaTimeMiliseconds;
// tick here
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment