What you want to do is interpolate the value of property of your game (sound volume, danger level, gravity etc.) let's call the variable you want to caluculate y
as some other property changes (like time, x-position etc.) let's call it t
.
We have n
points where we know the value of y
. Let's call each of these points p0
, p1
... pn-1
where each number is the index
of that point. Lets call the values in these points y0
, y1
... yn-1
.
So for any given value of t
we want to do the following:
First we find the two points closest to t
. Since all points are evenly spaced out we know that the value of t
for a given point is t = index/(n-1)
and by reordering this equation we can get the "index" of any given t like this index = t*(n-1)
. When t
isn't exactly in the same position as one of our points it's going to be a number in between the index values of the two closest points pk
and pk1
. So pk = floor(index)
gets you the index previous to your t
and pk1 = pk + 1
is the next point.
Then we have to find out how close t
is to each of these two points (value between 0 and 1) as that determines how much influence the value from each point will get in out interpolation. Let's call this measurement alpha
. Then alpha = (t - pk)/(pk1 - pk)
.
Finally if pk
and pk1
have values yk
and yk1
you get your interpolated value y
like this
y = (1-alpha)*yk + alpha*yk1;