Animation with Vector3.lerp in Unity
Hello everyone, today I will be showing you how to create a linear animation with linear interpolation in Unity. First, I will demonstrate how to make a button (“E”) move up and down without creating an animation clip, using a script instead.
In this article, I will be discussing how to use Vector3.lerp in Unity, which provides several solutions to this problem.
Step 1: I need this all fields to make it happen.
[Header("ButtonLabel Animation")]
[SerializeField]
private Vector3 m_startPosition;
[SerializeField]
private Vector3 m_endPosition;
private Vector3 m_originButtonLabel;
private float m_timeElapsed = 0;
[SerializeField]
private float m_lerpDuration = 3;
private bool m_isMoveUp = true;
private float m_interpolation;
Step 2: Create anAnimationButtonLabel()
private void AnimationButtonLabel() {}
My concept is very simple: move it from the starting position and stop it at the end position, then turn it around in another direction, like this.
m_interpolation = m_timeElapsed / m_lerpDuration;
if (m_isMoveUp) {
m_buttonLabel.transform.localPosition = Vector3.Lerp(m_startPosition, m_endPosition, m_interpolation);
} else {
m_buttonLabel.transform.localPosition = Vector3.Lerp(m_endPosition, m_startPosition, m_interpolation);
}
m_timeElapsed += Time.deltaTime;
As you see at the moment I didn’t deal anything with m_isMoveUp so let’s do it
if (m_timeElapsed >= m_lerpDuration) {
m_isMoveUp = !m_isMoveUp;
m_timeElapsed = 0;
}
The animation is controlled by ‘m_lerpDuration’. Once the duration is reached, the button should change its direction oppositely. Here’s the final code for the method:
private void AnimateButtonLabel()
{
m_interpolation = m_timeElapsed / m_lerpDuration;
if (m_isMoveUp) {
m_buttonLabel.transform.localPosition = Vector3.Lerp(m_startPosition, m_endPosition, m_interpolation);
} else {
m_buttonLabel.transform.localPosition = Vector3.Lerp(m_endPosition, m_startPosition, m_interpolation);
}
m_timeElapsed += Time.deltaTime;
if (m_timeElapsed >= m_lerpDuration) {
m_isMoveUp = !m_isMoveUp;
m_timeElapsed = 0;
}
}
I hope this article will assist you in creating animations with Vector3.lerp and enable you to have more fun with Unity.