Skip to content

Instantly share code, notes, and snippets.

@gamemachine
Last active February 12, 2019 07:02
Show Gist options
  • Save gamemachine/209676c14d383eb6c155e082825dca92 to your computer and use it in GitHub Desktop.
Save gamemachine/209676c14d383eb6c155e082825dca92 to your computer and use it in GitHub Desktop.
using System.Diagnostics;
using UnityEngine;
namespace Crest
{
[System.Serializable]
public class CrestTimeProvider
{
private const float MaxDifferenceBeforeAdjust = 0.5f;
[SerializeField]
private bool UseNetworkTime;
[SerializeField]
private bool HasNetworkTime;
[SerializeField]
private float CurrentWaterTime;
[SerializeField]
private float NetworkTime;
private Stopwatch Stopwatch;
public CrestTimeProvider(bool useNetworkTime)
{
UseNetworkTime = useNetworkTime;
}
public void SetNetworkTime(float networkTime)
{
NetworkTime = networkTime;
HasNetworkTime = true;
}
public float GetWaterTime()
{
// Prevents the water getting set to local time when using network time, which would result in speed waves as the system lerps from local to network.
if (UseNetworkTime && !HasNetworkTime)
{
return 0f;
}
if (NetworkTime == 0f)
{
NetworkTime = LocalNetworkTime();
}
if (CurrentWaterTime == 0f)
{
CurrentWaterTime = NetworkTime;
}
else
{
CurrentWaterTime += Time.deltaTime;
}
if (UseNetworkTime)
{
float diff = Mathf.Abs(CurrentWaterTime - NetworkTime);
if (diff >= MaxDifferenceBeforeAdjust)
{
CurrentWaterTime = Mathf.Lerp(CurrentWaterTime, NetworkTime, Time.deltaTime);
}
}
return CurrentWaterTime;
}
// Serves as a local time source when in single player mode, and as the time source for the server to send to clients.
public float LocalNetworkTime()
{
if (Stopwatch == null)
{
Stopwatch = Stopwatch.StartNew();
}
return Stopwatch.ElapsedMilliseconds / 1000f;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment