Moving platform algorithm

Hi!

I’m running through the 2D tutorial made by Unity3D team. The forumula they use to move the platform is this:

var weight = Mathf.Cos(Time.time * speed * 2 * Mathf.PI) * 0.5 + 0.5;
transform.position = targetA.transform.position * weight + targetB.transform.position * (1-weight);

I understand the first line that get the “weight” or the oscillation, but can anyone tell me where the second formula comes from? Some vector math theorem or what?

The second formula is simple linear interpolation (usually referred to as LERP).

(Also, I think Unity may already have a LERP function for vectors…)

Thanks, but while reading about LERP at wikipedia I couldn’t find anything that would lead me to that forumula used in the tutorial mentionend.

Any more hints? I would love how to understand how this formula was deduced.

Edit: I understand that the new vector (transform.position) can be “build” from adding a fraction of vector A (targetA) and vector B (targetB). But I’m looking for why this fraction is weight and 1-weight

The Wikipedia article is simply presenting LERP in a different context (that of a graph).

Try this instead. The formula given there is (I’m going to change the variable names for convenience):

p = A + t(B - A)

This formula basically ‘starts at A’, and then adds some amount of the difference between A and B to yield a point somewhere between A and B (assuming ‘t’ is in the range [0, 1]).

Now, let’s re-arrange this formula:

p = A + t(B - A)
p = A + tB - tA
p = tB + A - tA
p = tB + (1 - t)A

And we have the formula shown in your code example.

Another way to think of it is this. When ‘t’ is 0, you can see that we get ‘all’ of A and ‘none’ of B. Conversely, when ‘t’ is 1, we get ‘all’ of B and ‘none’ of A. Values of ‘t’ between 0 and 1 give us (in a linear progression) ‘some’ of A and ‘some’ of B. As ‘t’ increases, we get more B and less A (again, in a linear progression).

Does that make more sense?

Yes and thanks a million! :slight_smile:

Edit: And thanks for guiding me to that wiki, didn’t know about it before.