Linear Interpolation
Wed 15/01/2020
What is Linear Interpolation?
Unity Lerp - Er,... What?
Vector3.Lerp(Vector3 startPos, Vector3 endPos, float t)But how are you supposed to use it?
using UnityEngine;
using System.Collections;
public class LerpClass {
[SerializeField] private float animationTime;
[SerializeField] private Vector3 startPos;
[SerializeField] private Vector3 endPos;
public void MoveObject() {
StartCoroutine(nameof(MoveObjectUsingLerp));
}
private IEnumerator MoveObjectUsingLerp() {
// The normalised time which will go between 0 and 1
float normalisedTime = 0f;
// The time in seconds
float t = 0f;
while (t < animationTime) {
// Normalise the time
normalisedTime = t / animationTime;
// Move the gameObject, which has this script attached, from the
// start possition to the end position
transform.position = Vector3.Lerp(startPos, endPos, normalisedTime);
// Increment the time by Unity's delta time.
t += Time.deltaTime;
// Wait until the end of the frame.
yield return null;
}
// The normalised t value will never reach 1 so move the gameObject,
// which has this script attached, to the end position.
transform.position = endPos;
}
}Last updated