Mathf.Lerp(5.0f, 15.0f, 0f); // returns 5.0f
Mathf.Lerp(5.0f, 15.0f, 0.5f); // returns 10.0f
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!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?
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);
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 timer is on, do animation
if(Time.time < bounceTimer)
{
// Calculate valid time for curve (in between 0 and 1)
float scaleTime = (bounceTimer - Time.time) / 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(scaleTime);
}
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
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
.