Analysis of linear interpolation lerp () function in Unity3d

Source: Internet
Author: User

Transferred from: http://www.aichengxu.com/view/2446604

In Unity3d, the linear interpolation function lerp () is often used to interpolate between the two, which can be between two materials, two vectors, two floating-point numbers, and two colors, with the following function prototypes:

1.material.lerp interpolation

function Lerp (start:material, End:material, t:float): void

Interpolation between two materials



2.vector2.lerp interpolation

Static Functionlerp (From:vector2, To:vector2, t:float): Vector2

The linear interpolation between the two vectors. Interpolates between form and to-to by the number T.

T is sandwiched between 0 and 1. When t=0, returns from. When T=1, return to. When t=0.5, put back the average between from and to.

3.vector3.lerp interpolation

Static Functionlerp (From:vector3, To:vector3, t:float): Vector3

The linear interpolation between the two vectors. Interpolates between from and to by the number T.

4.vector4.lerp interpolation

Static Functionlerp (From:vector4, To:vector4, t:float): Vector4

The linear interpolation between the two vectors. Interpolates between from and to by the number T. T is the value that is sandwiched between [0...1]. , when t = 0 o'clock, returns from. When t = 1 o'clock, return to. When t = 0.5 returns the average of the From and to.



5.mathf.lerp interpolation

Static Functionlerp (From:float, To:float, t:float): float

Returns the interpolation between A and b based on the floating-point number T, which is limited to 0~1. When t = 0 returns from, when t = 1 returns to. When t = 0.5 returns the mean of the From and to.



6.color.lerp interpolation

Static Functionlerp (A:color, B:color, t:float): Color

Interpolates between Colors A and B by T.

"T" is a value sandwiched between 0 and 1. When T is 0 o'clock returns the color A. When T is 1 o'clock returns the color B.



Interpolation, from the literal point of view, is to insert a value in between, is this understanding correct? Let's begin by analyzing the simplest floating-point interpolation function:

Mathf.lerp interpolation

Static Functionlerp (From:float, To:float, t:float): float

Returns the interpolation between A and b based on the floating-point number T, which is limited to 0~1. When t = 0 returns from, when t = 1 returns to. When t = 0.5 returns the mean of the From and to.



First, let's do an experiment, start Unity3d, either build a script file, and enter the following in its start ():

void Start () {
Print (Mathf.lerp (0.0f, 100.0f,0.0f). ToString ());
Print (Mathf.lerp (0.0f, 100.0f,0.1f). ToString ());
Print (Mathf.lerp (0.0f, 100.0f,0.2f). ToString ());
Print (Mathf.lerp (0.0f, 100.0f,0.3f). ToString ());
Print (Mathf.lerp (0.0f, 100.0f,0.4f). ToString ());
Print (Mathf.lerp (0.0f, 100.0f,0.5f). ToString ());
Print (Mathf.lerp (0.0f, 100.0f,0.6f). ToString ());
Print (Mathf.lerp (0.0f, 100.0f,0.7f). ToString ());
Print (Mathf.lerp (0.0f, 100.0f,0.8f). ToString ());
Print (Mathf.lerp (0.0f, 100.0f,0.9f). ToString ());
Print (Mathf.lerp (0.0f, 100.0f,1.0f). ToString ());
}

Run Unity and the console will print out:



This experiment is interpolated between 0 and 100, what value to insert, depending on the 3rd parameter, from the printed results can be seen, the 3rd parameter is a scale factor, is 0.1 is 0 to 100 of the length of One-tenth, the same, 0.2 means two-tenths, and so on. From this point of view, the interpolation that we have literally understood at first is the insertion of a value that can be understood.

If we change the first parameter in the interpolation function in the above script to 100.0f, the second parameter becomes 110.0f, the third parameter remains the same, what do you think of the result of the operation? Do not consider it to be 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 yo, the actual result is 100, 101, 102, 103, 104, 105, 106 ...., because interpolation is the value in the original two number, which means that the function is first based on the ratio given by the third parameter to calculate the net increment , plus the starting number, which finally calculates the interpolated value.

In the Unity3d game development, the most applied is the vector3.lerp vector interpolation, below we use this interpolation to guess the internal implementation mechanism and some applications.



, there are two points a (0,10,0) and B (10,0,-10) in the space, we inserted a C point between A and B two points, assuming that the position of the C point in the AB two-fifths, that is, ac/ab=0.4, according to the corresponding edge of the similar shape of the geometric knowledge of the middle school, in the ⊿abo ac/ab=od /ob, the same as in the ⊿OBF od/ob=oe/of, so ac/ab=od/o=oe/of = 0.4, the C point of the x-coordinate value is: oe=0.4*of=0.4*10=4.

According to, also know ed/fb=0.4, so C point Z coordinate value de=0.4*bf=0.4* (-10) =-4.

For the y-coordinate values of the C point, see:



eo/ao=df/af=cb/ac=1-0.4=0.6, the y-coordinate value of the C point is eo=0.6*ao=0.6*10=6.

In summary, the C-point three-dimensional coordinates are C (4,6,-4).

Below we take advantage of the vector3.lerp interpolation function in Unity3d: static function Lerp (From:vector3, To:vector3,
T:float): Vector3 to calculate the interpolation of the above calculation.

We rewrite the start () function in the previous script to:

void Start ()
{Print (Vector3.lerp (NewVector3 (0, 0), NewVector3 (10,
0, -10), 0.4f). ToString ()); }
The result of this operation is:



This is consistent with the results of our calculations.

The above calculation, for the sake of simplicity, a, b two points to obtain a more special, reduce the complexity of the calculation. And to the normal A, b two points, as shown:



We can also get the triangular egl and triangle EFK, using the same method to calculate the length of hi, plus the length of OH is the X coordinate of the C point. The same method can be used to push the coordinates of Y and Z. The manual calculation is very complex, and the LERP function can efficiently return this interpolation for us, we make the calculation here, just to help us to speculate lerp the function of the internal implementation mechanism, but also, in practice, all work is to lerp function to complete.

The LERP function is used more in the game development process, and in Unity's help document we have an example of the two applications of Vector3.lerp, one in which the animation position moves from start.position to end.position in 1 seconds:

Using unityengine;usingsystem.collections;public classexample:monobehaviour {public         Transform start;         Public Transform end;         void Update ()          {                   transform.position =vector3.lerp (start.position, end.position, time.time);}         }



Another example:

Follow a target object like a spring

Using unityengine;usingsystem.collections;public classexample:monobehaviour {public         Transform target;         public float smooth = 5.0F;         void Update ()          {                   transform.position =vector3.lerp (transform.position, target.position, Time.deltatime * smooth);}         }



The transform.position in this example is the spatial coordinates of the object to be followed, the target.position is the spatial coordinates of the object, and the result of the whole sentence is to change the coordinates of the following objects continuously into the interpolation between them, but over time, the value of the third parameter will eventually be 1, so the most The position of the end follower will coincide with the target object. We used to play the game, the protagonist attached to a pet, such as the Eagle, the protagonist moves, the Eagle will follow with flying, the protagonist moves fast it flies fast, always will not leave the protagonist, using lerp interpolation function can be achieved.

Let's look at another application example.



This is a cool running game scene, the prisoner along a forest road forward, behind a police car chase, in front of a roadblock, in the course of the game, we will be in the prisoner run on a fixed route randomly generated roadblocks, and the road is not straight, both bent, and ups and downs, by the program randomly generated roadblocks how to determine its space position? At this point, the Lerp function comes in handy.

First, according to the bending and fluctuation of the road, set an empty object at the turning point, the position value of this empty object is the space coordinate and the road is consistent, we refer to the points of these empty objects as the road turning point, and the multi-segment lines formed by these points are connected to the pavement, which is the approximate path of the road. The more and more accurate these points are, the higher the similarity of the path to the road.

Now let's take that path instead of the road, and place the randomly generated roadblock on this path, which is on the road.

Suppose we want to create a roadblock every 100 to 200 meters, with variable z + = Random.range (100, 200) Record the z-coordinate value of the roadblock (as the prisoner is generally running along the z-axis) and then determine, based on this z-coordinate, which of the two points in the previously set inflection point, when found, interpolates between the two points, and its interpolated proportional factor (LERP () The 3rd parameter of the function) can be calculated from two turning points and the z-coordinate values known in the three points of this interpolation point, so that the Vector3.lerp
(From:vector3, To:vector3, t:float) The three parameter values in the function are known, it can calculate the interpolation point of the spatial coordinates, according to the previous design, the line between the two turning points is attached to the road, Then the coordinates of this interpolation is on the road, and according to this interpolation placed roadblocks will not deviate from the road, and will follow the road left to turn to the left, right turn to the right, uphill and uphill, downhill and downhill.

The specific design process is as follows:

Import the corridor model, assuming it is named Forest_1. The model is designed so that its length is 3000 and the origin of the coordinates is on its terminal. After the import, we place it in the scene in the positive direction of the z axis, so that its transorm.position x and Y values are 0. We can import multiple segments of the same type of road model by controlling their Z-values to stitch them up into long forest roads.

Create an empty object on this road object as its sub-object, named Waypoint, and then create a number of empty empty objects under it, named Waypoint_01, waypoint_02 ..., put them in the corner of the road, and by magnifying, Rotate the scene map and fine-tune the coordinates of these sun objects so that they fit with the road surface as shown:



Description: The green button block in the figure is these empty objects, because they are empty objects, cannot be displayed in the scene, it is through the properties panel to set a display for editing the use of the icon indicator.




In this way, we divided the winding road into a section of the straight road, and recorded the points of each section of the two sides of the characteristics of the coordinate values. With these feature points, there is also a route similar to the road. This is a straight way of warping, bending and undulating the road into a similar segment. The more such points are, the higher their similarity.

Create a Script component on Waypionts Waypionts.cs:

Using unityengine;using System.collections;public class Waypoints:monobehaviour {public    transform[] points;    void Ondrawgizmos ()    {        itween.drawpath (points);    }}



Public transform[]points; the points defined by this sentence is the array that holds those feature points, because it is public and can be assigned values in the Unity editing interface. It does this by selecting the Waypoints control in the hierarchy view, then clicking the icon in its Inspector view to lock its Inspector panel, and then selecting all hierarchy to waypoint_01 in Waypiont_ view After 11, you can complete the assignment by dragging to the array name points on the properties panel, such as




Next, add a script that generates roadblocks to the Forestcs.cs Script component established on this forest road:

<span style= "" >using unityengine;using System.Collections;     public class Forest:monobehaviour {public gameobject[] obstacles;   Barricade Object array public float startlength = 50;   The roadblock appears on the road where the starting position is public float minLength = 100;   The minimum distance from the previous roadblock public float maxLength = 200;        The maximum distance from the previous roadblock private Transform player;    The protagonist of the game-runner's transform component private waypoints waypoints; The script component on the route that fits the road is void awake () {player = Gameobject.findgameobjectwithtag (tags.player). Transform;//Find the game owner The male-runner and obtains its transform component waypoints = transform. Find ("waypoints").  Getcomponent<waypoints> ();    Find the script component on the route that fits the pavement}//Use this for initialization void Start () {generateobstacle (); When the Forest road is created, the start () method is called automatically to call this Generateobstacle () method}//If the protagonist runs out of this road, notify the Generateforest class to start running to produce a new road, and destroy the road that ran out void Update () {if (Player.position.z > transform.position.z+100) {camer A.main.sendmessage ("GeneratefOrest ");        Gameobject.destroy (This.gameobject);  }} void Generateobstacle () {float Startz = transform.position.z-3000;          The starting z-coordinate of the current road in the scene is float EndZ = transform.position.z;             The end z-coordinate of the current road in the scene is float z = startz + startlength;            The z-coordinate of the roadblock to be generated while (true) {z + = Random.range (100, 200);                 A roadblock is generated every 100 meters. if (z > EndZ)//If a roadblock is to be created beyond this road, exit the roadblock and create a loop, or a roadblock will be created.            Break                    } else {Vector3 position = Getwayposbyz (z); Call the Getwayposbyz () method to calculate the roadblock position coordinates int obsindex = random.range (0, obstacles.      Length);            Generates a random ordinal number gameobject.instantiate (Obstacles[obsindex], position, quaternion.identity) that takes a roadblock from an array of roadblocks;//instance of a roadblock       }}} Vector3 Getwayposbyz (float z) {transform[] points = waypoints.points;   Set of turning points on the road     int index = 0; The ordinal number of the turning point in the set for (int i = 0; i < points. Length-1; i++) {//based on the z-value of the roadblock to be inserted in the collection, look for between the two points, and then write down the ordinal number if (Z<=points[i].position.z && Z>=points[i+1].po                SITION.Z) {index = i;            Break }}//Use the LERP function to calculate the spatial coordinate value of the insertion barrier at return vector3.lerp (Points[index + 1].position, Points[index].position, (    Z-points[index + 1].position.z)/(Points[index].position.z-points[index +1].position.z)); }}</span>



Documents: Click to open link

Analysis of linear interpolation lerp () function in Unity3d

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.