-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathGetCurveTimeForValue.cs
28 lines (22 loc) · 1005 Bytes
/
GetCurveTimeForValue.cs
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
public float GetCurveTimeForValue(AnimationCurve curveToCheck, float value, int accuracy)
{
float startTime = curveToCheck.keys[0].time;
float endTime = curveToCheck.keys[curveToCheck.length - 1].time;
float nearestTime = startTime;
float step = endTime - startTime;
for (int i = 0; i < accuracy; i++)
{
float valueAtNearestTime = curveToCheck.Evaluate(nearestTime);
float distanceToValueAtNearestTime = Mathf.Abs(value - valueAtNearestTime);
float timeToCompare = nearestTime + step;
float valueAtTimeToCompare = curveToCheck.Evaluate(timeToCompare);
float distanceToValueAtTimeToCompare = Mathf.Abs(value - valueAtTimeToCompare);
if (distanceToValueAtTimeToCompare < distanceToValueAtNearestTime)
{
nearestTime = timeToCompare;
valueAtNearestTime = valueAtTimeToCompare;
}
step = Mathf.Abs(step * 0.5f) * Mathf.Sign(value - valueAtNearestTime);
}
return nearestTime;
}