Skip to content

SmoothedValues: Lerping with Sanity

Mike edited this page Jun 3, 2015 · 6 revisions

SmoothedValue subclasses were made to address the propensity to misuse Lerps in Unity. It is a common pattern to do things like target follow and other movement via Lerp( from, to, Time.deltaTime * someValue ). Lerping like that isn't really doing much more than jumping towards the to value with an exponential out ease. The target will never reach the to value. It also introduces framerate dependency. Moving 2% towards a destination 60 times per second is not the same as moving 4% towards a destination 30 times per second.

SmoothedValues will do the same basic thing with 2 major differences: you can choose the ease type and the target will reach the to value with the same curve independent of framerate.

Now is a good time to note that SmoothedValues are best used for things that do not change their target value too often. If you are looking for something that will assist with moving towards a target that is moving checkout Zest.lerpTowards which can be used as a drop-in replacement for the incorrect usage of Lerp explained above.

When to Use SmoothedValues

There are lots of places where using SmoothedValues can come in handy. Basically, any place where you have some target value (float, Vector2, Vector3 currently supported) that you want to smoothly move towards are great candidates for SmoothedValues. You can set the target value once or whenever it changes so they are flexible enough to handle most situations. Things like a camera y offset that shifts when holding down/up (think Spelunky), a camera zoom that might get interrupted and want to bounce around to different values.

Usage

We will use a Vector3 in this example since that is the most commonly used type for this kind of stuff (Transform.position). First, you need to declare the SmoothedValue in your class and create it in Awake/Start:

SmoothedVector3 _smoothedVector3;

void Awake()
{
	_smoothedVector3 = new SmoothedVector3( transform.position, 0.5f );
	// optionally set the ease type
	_smoothedVector3.easeType = EaseType.QuartOut;
}

The SmoothedValue needs to know the current value (transform.position in our example) and how long it should take to reach the target value. At some point later you may want to move towards a new target position. You do this by calling setToValue. You will want to call setToValue every time the target changes. Internally, the SmoothedValue will reset itself and continue to ease towards the target.

_smoothedVector3.setToValue( newTargetValue );

In Update, you will want to actually use the SmoothedValue. You do this by accessing the value property.

void Update()
{
	transform.position = _smoothedVector3.value;
}

Clone this wiki locally