-
Notifications
You must be signed in to change notification settings - Fork 23
SmoothedValues: Lerping with Sanity
SmoothedValue subclasses were made to address the propensity to misuse Lerps in Update/FixedUpdate/Coroutines. It is a common pattern to do things like camera 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.
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 when duration seconds has passed.
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.
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;
}