【Unity】线性插值


在unity3D中经常用线性插值函数Lerp()来在两者之间插值,两者之间可以是两个材质之间、两个向量之间、两个浮点数之间、两个颜色之间。

为了更好的理解线性插值的概念,我们先讨论一下浮点数的线性插值

浮点数的线性插值

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
void Start()
{
Debug.Log(Mathf.Lerp(0, 100, 0).ToString());
Debug.Log(Mathf.Lerp(0, 100, 0.1f).ToString());
Debug.Log(Mathf.Lerp(0, 100, 0.2f).ToString());
Debug.Log(Mathf.Lerp(0, 100, 0.3f).ToString());
Debug.Log(Mathf.Lerp(0, 100, 0.4f).ToString());
Debug.Log(Mathf.Lerp(0, 100, 0.5f).ToString());
Debug.Log(Mathf.Lerp(0, 100, 0.6f).ToString());
Debug.Log(Mathf.Lerp(0, 100, 0.7f).ToString());
Debug.Log(Mathf.Lerp(0, 100, 0.8f).ToString());
Debug.Log(Mathf.Lerp(0, 100, 0.9f).ToString());
Debug.Log(Mathf.Lerp(0, 100, 1).ToString());
}

// 结果为
// 0
// 10
// 20
// ....
// 90
// 100

可以看出输出的结果最终取决于第三个参数
如果将第一个参数改为100,第二个参数改为110,第三个参数不变,那么结果为100,101,102,103,104,105,106,107,108,109,110。

向量的线性插值

1
2
3
4
void Update()
{
transform.position = Vector3.Lerp(A, B, Time.time);
}

该物体会慢慢的移动到从A移动到B