blob: efb96f3745c595317bfa006fd0d307b97a5c6896 (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
|
using UnityEngine;
[DisallowMultipleComponent]
[DefaultExecutionOrder(ORDER_EXECUTION)]
public class InterpolationFactorController : MonoBehaviour
{
public const int ORDER_EXECUTION = -1000;
private static InterpolationFactorController Instance;
private float[] _lastFixedUpdates = new float[2];
private int _lastIndex;
public static float Factor { get; private set; }
private void Awake()
{
if (Instance)
{
Destroy(this);
Debug.LogWarning($"The '{typeof(InterpolationFactorController).Name}' is a singleton!");
return;
}
Instance = this;
Factor = 1;
}
private void Start()
{
_lastFixedUpdates = new float[2] { Time.fixedTime, Time.fixedTime };
_lastIndex = 0;
}
private void FixedUpdate()
{
_lastIndex = NextIndex();
_lastFixedUpdates[_lastIndex] = Time.fixedTime;
}
private void Update()
{
float lastTime = _lastFixedUpdates[_lastIndex];
float prevTime = _lastFixedUpdates[NextIndex()];
if (lastTime == prevTime)
{
Factor = 1;
return;
}
Factor = (Time.time - lastTime) / (lastTime - prevTime);
}
private int NextIndex()
{
return (_lastIndex == 0) ? 1 : 0;
}
}
|