What are your options to animate objects using scripting in Unity3D? On of them is interpolating the values with the Lerp function. In this tutorial you will learn how to use an AnimationCurve and Vector3.Lerp() to move a cube to a random position in space.

Using AnimationCurve and Vector3.Lerp to animate an object in Unity.

animate cube

Create cube and script

A script is now attached to your cube.

script

Your class should look like this:

using UnityEngine;

public class Mover : MonoBehaviour
{
public AnimationCurve MoveCurve;

private void Start()
{
}

private void Update()
{
}
}

curve

The Curve editor opens

curve

using UnityEngine;

public class Mover : MonoBehaviour
{
public AnimationCurve MoveCurve;

private Vector3 _target;
private Vector3 _startPoint;
private float _animationTimePosition;

private void Start()
{
UpdatePath();
}

private void Update()
{
if (_target != transform.position)
{
    _animationTimePosition += Time.deltaTime;
    transform.position = Vector3.Lerp(_startPoint, _target, MoveCurve.Evaluate(_animationTimePosition));
}
else
{
    UpdatePath();
    _animationTimePosition = 0;
}
}

private void UpdatePath()
{
_startPoint = transform.position;
_target = Random.insideUnitSphere;
}
}

The Update method checks if the cube is at the target position. If it is not, the position will be calculated by the Lerp function.

How does the Lerp function work?

The Lerp function takes a starting and target vector and a position between 0 and 1. The next graph shows a Vector2 Lerp function.

curve

In the script above the Lerp position _animationTimePosition starts at zero and is updated on each frame. When the cube is at its target position _animationTimePosition is reset to zero and a random new target position is being calculated.

Written by Loek van den Ouweland on 2017-10-13.
Questions regarding this artice? You can send them to the address below.