69 lines
2.3 KiB
C#
69 lines
2.3 KiB
C#
using System;
|
|
using UnityEngine;
|
|
|
|
namespace NEG.Utils.Timing
|
|
{
|
|
public class TimeMachine
|
|
{
|
|
private double timeInternal;
|
|
|
|
public TimeMachine()
|
|
{
|
|
timeInternal = 0;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Adds time into the TimeMachine
|
|
/// </summary>
|
|
/// <param name="time">Amount of time to be added</param>
|
|
public void Accumulate(double time) => timeInternal += time;
|
|
|
|
/// <summary>
|
|
/// Retrieves given amount of time from the TimeMachine
|
|
/// </summary>
|
|
/// <param name="maxTime"></param>
|
|
/// <returns>Amount of time retrieved</returns>
|
|
public double Retrieve(double maxTime)
|
|
{
|
|
if (!double.IsFinite(maxTime))
|
|
{
|
|
double timeRetrieved = timeInternal;
|
|
timeInternal = 0;
|
|
return timeRetrieved;
|
|
}
|
|
|
|
double timeLeft = timeInternal - maxTime;
|
|
timeInternal = Math.Max(timeLeft, 0);
|
|
return Math.Min(maxTime + timeLeft, maxTime);
|
|
}
|
|
|
|
/// <summary>
|
|
/// Attempts to retrieves given amount of time from the TimeMachine <br />
|
|
/// If there is enough <paramref name="time" /> accumulated in this machine subtracts that amount and returns true,
|
|
/// otherwise returns false
|
|
/// </summary>
|
|
/// <param name="time"></param>
|
|
public bool TryRetrieve(double time)
|
|
{
|
|
if (!(timeInternal >= time))
|
|
return false;
|
|
timeInternal -= time;
|
|
return true;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Result is equivalent to calling <see cref="TryRetrieve(double)" /> as many times as possible, but is faster for
|
|
/// larger <paramref name="limit" /> values
|
|
/// </summary>
|
|
/// <param name="interval">Single unit of warp time, must be positive</param>
|
|
/// <param name="limit">Maximum amount of warps, must be positive</param>
|
|
/// <returns>Amount of warps</returns>
|
|
public int RetrieveAll(double interval, int limit = int.MaxValue)
|
|
{
|
|
int result = Mathf.FloorToInt((float)(timeInternal / interval));
|
|
result = Math.Clamp(result, 0, limit);
|
|
timeInternal -= result * interval;
|
|
return result;
|
|
}
|
|
}
|
|
} |