In game development, one of the most common problems is the smooth transition of objects from one position to another. A linear interpolation or Lerp function is a popular technique used to achieve this in Unity. In this blog post, we will explore the lerp function in Unity and its implementation.
This post was originally posted at https://agrawalsuneet.github.io/blogs/lerp-function-unity/ , later reposted on Medium.
What is Lerp Function?
The Lerp function stands for linear interpolation.
The function returns a value that is a linear interpolation between the starting and ending values, based on the weight parameter. It takes three arguments:
- The starting value
- The end value
- A weight between 0 and 1 representing the percentage of the value between the start and end values.
In case of linear transformation, the Lerp function calculates the position along the line that corresponds to the input value. When the input value is 0, the function returns the starting position, and when the input value is 1, it returns the target position. For values between 0 and 1, it returns a position that is between the two endpoints.
Implementation of Lerp Function
Unity provides a built-in Lerp function that can be used to interpolate between two positions. The function is called Lerp and can be called using the following syntax:
Vector3.Lerp(startPosition, targetPosition, t);
This function takes the startingPosition, targetPosition, and a value t between 0 and 1 representing the percentage of the distance between the two positions. It returns the position that is t percent of the way from the starting position to the target position.