float x1 = Mathf.Lerp(5.0f, 15.0f, 0f); // returns 5.0f
float x2 = Mathf.Lerp(5.0f, 15.0f, 0.5f); // returns 10.0f
float x3 = Mathf.Lerp(5.0f, 15.0f, 1.0f); // returns 15.0f
Mathf.Lerp
is clamps the returned value automatically
Mathf.LerpUnclamped
, the value is extrapolated when outside the limits!a
to b
, while time moves forward.[SerializeField] Transform endTransform;
[SerializeField] float lerpDuration;
Vector3 startPosition;
float startTime;
bool lerping = false;
void StartLerp() {
startTime = Time.time;
lerping = true;
}
void UpdateLerp() {
if (!lerping) return
float time = (Time.time - startTime) / lerpDuration;
transform.position = Vector3.Lerp(startPosition, endTransform.position, time);
if (time > 1) lerping = false;
}
void Update() {
if (Input.GetKey("space")) StartLerp();
UpdateLerp();
}
After pressing a button once, lerp GameObject's color from red to blue.
Bonus: After pressing twice, lerp the color back to red.
Bonus bonus: What if you press the button during lerping?
for custom interpolation curves, use the AnimationCurve
variable
[SerializeField] AnimationCurve curve;
The curve can be manipulated in the inspector:
Mathf.Lerp
curve.Evaluate(t)
returns a value from the graph (by default, between 0 and 1)
Mathf.Lerp(a, b, t)
Mathf.Lerp(a, b, curve.Evaluate(t))
public AnimationCurve bounce;
...
if(startTime > 0) // If we have set a startTime, do the interpolation
{
// Calculate valid time for curve (between 0 and 1)
float time = (Time.time - startTime) / bounceLenght;
// Get the value from curve at the time of the animation
// and multiply it with the desired scaled axis
// then add it to default scale (1, 1, 1)
transform.localScale = Vector2.one + axis * bounce.Evaluate(time);
}
transform.position = Vector3.Lerp(transform.position, target.position, Time.deltaTime);
deltaTime
...? What!?This is bad! We get different results with different machines!
There's a somewhat-known solution to this
source = Mathf.Lerp(source, target, smoothing * Time.deltaTime);
source = Mathf.Lerp(source, target, 1 - Mathf.Pow(smoothing, Time.deltaTime))
Read more here: Frame rate independent damping using lerp
Vector3 relativePos = target.position + new Vector3(0,.5f,0) - transform.position;
transform.localRotation =
Quaternion.Slerp(
transform.localRotation,
Quaternion.Lookrotation(relativePos),
Time.deltaTime
);
transform.Translate(0,0, 3 * Time.deltaTime);
Mathf.InverseLerp(a, b, x)
What if we want to map a range
Or in other words, map a variable input
in range inputMin
inputMax
outputMin
outputMax
.The function that achieves this is a sort of a "generalization" of lerp & inverse lerp:
float Remap (float inputMin, float inputMax, float outputMin, float outputMax, float input)
{
float t = Mathf.InverseLerp(inputMin, inputMax, input );
return Mathf.Lerp( outputMin, outputMax, t );
}
input
has the value of inputMin
, the function returns the value outputMin
.