Tuesday, November 17, 2015

Capstone Post 6: Interpolating Given Time

Linear Interpolation is a hugely powerful technique, and can be very easy to implement in your code! If you implement it properly. Simply, it is a function of time which returns a value between an initial value (a) and a final value (b), given a time (t). Time (t) is a normalized value which represents the fraction of how far along in the Lerp we are. Calling it time is a bit misleading, but bear with me.

Knowing this, let's take a look at the whole one line of code that let's us interpolate given an a, b, and t:

Taking a look at the above function, let's plug in some example values. If I am Lerping between 5 (a) and 15 (b), and I am 0% of the way there (t = 0.0), this function will return 5. If I am 100% of the way there (t = 1.0), then it will return 15. If I am 50% of the way there (t = 0.5), this function will return 10.

Now that we understand how Lerping fundamentally functions, let's do something super simple with it: move from point a to point b in Unity C#. A really simple interpolation we often must perform is moving something a distance in a given amount of time. Well here ya go, pretty much exactly as you might have expected:


It's as easy as that! But by no means does Lerp stop here. What Lerp is really good at is interpolating anything. Position, rotation, color, velocity, acceleration, scale, even strings of text! Anything with a start and desired value can be interpolated between.

The real power of linear interpolation heck yeah there's more comes in to play when we do fun things with our t variable. A graph of the distance over the time for the above code would look something like this:



Very simple. However, we can run t through ANY function and it will interpolate properly as long as we normalize it to [0.0, 1.0]. What this means is we can turn ANY graph into a change in position, rotation, color, etc.


smooth: t = t*t*(3-2*t)
smoother: t=t^3*(t*(6*t-15)+10)
If you can graph it, you can run t through a function and Lerp it that way. Have fun out there!












No comments:

Post a Comment