Math in Unity : Linear Interpolation(Part I)
To better understand linear interpolation, let’s make an example immediately.
Let’s say we have two points, Point A and Point B, and consider the distance between the two points as the Vector v.
Now, we know that the formula for finding Point B is simply
Point A plus the Vector
B = A + v
Now, if instead of finding point B, we wanted to find a point A MIDDLE between Point A and Point B, what would the formula be?
Well, we should divide the Vector by two, so we’re going to add half Vector to point A to find point A HALF between Point A and Point B, okay?
B = A + v * 0.5f
This same principle will be applied to find a quarter of the segment
B = A + v * 0.25f
Following these formulas, we can see that Point A is at 0 while Point B is at 1.
Consequently the formula will become
B = A + v*t
Where t is the interval between 0 and 1 INCLUSIVE.
This formula is applicable to both LINES, SEGMENTS, and RAYS, with the only difference that the range of t is different in all three cases.
SEGMENTS : 0 < = t < = 1
LINES : - ∞ < = T < = ∞
RAYS : 0 < = T < = ∞
The best way to understand, as always, is to try it in code.
I have a really simple setup for this text, a sphere between two cubes.
Feel free to use whatever you want.
Now, first of all I move sphere little bit out
So I create a C # script, Sphere, and write these simple lines of code
That is very simple to explain.
We have two Transforms for Point A and Point B, Vector v is simply the Distance between B and A,
and in the Move method (float t) I take the formula we have seen and copy it.
If we try, the result is this
As we have seen, the sphere resets itself in what should be the position we give it.
0.3f, so a third of the distance.
To make sure it’s working, let’s try 0.8f for example
At 0.8f, the sphere is much closer to the second cube.
So far, so good.
But what if we use, for example, Time.time as the float?
As time continues to flow, the sphere continues to move starting from Point A, without ever stopping, as if it were a RAY or a LINE.
In the next article we see how to fix this behaviour, and make the sphere moves from Point A to Point B.