Unexpectedly for myself, I’m hung up on this issue.
Suppose there is an array with a length of N elements. And we need to take an element from there, but not by index, but by value t = [0…1] (from 0 to 1 both inclusive).
That is, the problem is reduced to a linear interpolation of the float value into the index of the array.
int index = (int) Mathf.Lerp(0, N, t);
But when t = 1
, then index = N
which is out of array’s range.
We can fix this as follows:
int index = Mathf.Clamp((int) Mathf.Lerp(0, N, t), 0, N - 1);
or
int index = (int) Mathf.Lerp(0, N, t - Mathf.Epsilon);
but i dont like the way it looks.
So the question is how to do this gracefully?