aboutsummaryrefslogtreecommitdiff
path: root/JamHelper/Assets/Scripts/Smooth-Motion-in-Unity/InterpolationFactorController.cs
diff options
context:
space:
mode:
authorchai <chaifix@163.com>2022-02-17 19:42:30 +0800
committerchai <chaifix@163.com>2022-02-17 19:42:30 +0800
commite5d082b220eaa4351086b27607231f5df01a0903 (patch)
tree49f8ea1678889ee0c3b902eaa107e32551b27df1 /JamHelper/Assets/Scripts/Smooth-Motion-in-Unity/InterpolationFactorController.cs
parent701113cf63da4115f932b6cfb89cd52828ffa405 (diff)
*misc
Diffstat (limited to 'JamHelper/Assets/Scripts/Smooth-Motion-in-Unity/InterpolationFactorController.cs')
-rw-r--r--JamHelper/Assets/Scripts/Smooth-Motion-in-Unity/InterpolationFactorController.cs58
1 files changed, 58 insertions, 0 deletions
diff --git a/JamHelper/Assets/Scripts/Smooth-Motion-in-Unity/InterpolationFactorController.cs b/JamHelper/Assets/Scripts/Smooth-Motion-in-Unity/InterpolationFactorController.cs
new file mode 100644
index 0000000..efb96f3
--- /dev/null
+++ b/JamHelper/Assets/Scripts/Smooth-Motion-in-Unity/InterpolationFactorController.cs
@@ -0,0 +1,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;
+ }
+}