文章目录线性插值Mathf.Lerp控制灯光强度Vector3.Lerp物体的空间运动Color.Lerp颜色渐变线性插值线性插值是指找到两个给定值之间的某个百分比值。L e r p a ( b − a ) ∗ t t ∈ [ 0 , 1 ] Lerp a (b - a) * tt∈[0,1]Lerpa(b−a)∗tt∈[0,1]例如我们可以在数字3和5之间线性插值50%得到数字4。这是因为4在3和5之间占了50%。Unity中通过Lerp的函数实现。包括Mathf.Lerp、Color.Lerp和Vector3.Lerp。Mathf.LerpMathf.Lerp会自动将插值因子 t 限制在 [0, 1] 区间内。而Mathf.LerpUnclamped则允许 t 超出范围。float result Mathf.Lerp (3f, 5f, 0.5f); // result 4设a 3 a 3a3b 4 b 4b4插值因子t 0.5 t 0.5t0.5则插值结果为4f ( t ) a ( b − a ) ∗ t 3 ( 4 − 3 ) ∗ 0.5 4 \begin{aligned} f(t) a(b-a)*t\\ 3(4-3)*0.5\\ 4 \end{aligned}f(t)a(b−a)∗t3(4−3)∗0.54控制灯光强度在某些情况下Lerp函数可以用来随时间平滑一个值。void Update () { light.intensity Mathf.Lerp(light.intensity, 8f, 0.5f); }如果灯光强度是0那么第一次更新后会被设置为4。下一帧会先是6然后7再7.5依此类推。因此在多个帧内光的强度会趋近8但随着接近目标变化速度会减慢。注意这种情况发生在多个帧内。如果我们希望这不依赖帧率务必使用Time.deltaTime来缩放插值速度。void Update () { light.intensity Mathf.Lerp(light.intensity, 8f, 0.5f * Time.deltaTime); }这意味着强度的变化将是每秒发生而不是每帧。平滑值时通常最好使用SmoothDamp函数。只有确定想要的效果时才用Lerp平滑。Vector3.LerpVector3 from new Vector3(1f, 2f, 3f); Vector3 to new Vector3(5f, 6f, 7f); Vector3 result Vector3.Lerp(from, to, 0.75f); // result (4, 5, 6)在线性变换中a ⃗ [ 1 2 3 ] , b ⃗ [ 5 6 7 ] , t 0.75 \vec{a} \begin{bmatrix}1 \\ 2 \\ 3\end{bmatrix}, \vec{b} \begin{bmatrix}5 \\ 6 \\ 7\end{bmatrix}, t 0.75a123,b567,t0.75则插值结果为[ 4 5 6 ] \begin{bmatrix}4 \\ 5 \\ 6\end{bmatrix}456向量插值的计算u ⃗ a ⃗ ( b ⃗ − a ⃗ ) ∗ t [ 1 2 3 ] ( [ 5 6 7 ] − [ 1 2 3 ] ) ∗ 0.75 [ 1 2 3 ] [ 4 4 4 ] ∗ 0.75 [ 1 2 3 ] [ 3 3 3 ] [ 4 5 6 ] \begin{aligned}\vec{u} \vec{a} (\vec{b} - \vec{a}) * t\\ \begin{bmatrix}1 \\2 \\ 3\end{bmatrix} (\begin{bmatrix}5 \\ 6 \\ 7\end{bmatrix} - \begin{bmatrix}1 \\ 2 \\ 3\end{bmatrix}) * 0.75\\ \begin{bmatrix}1 \\2 \\ 3\end{bmatrix} \begin{bmatrix}4 \\ 4 \\ 4\end{bmatrix} * 0.75\\ \begin{bmatrix}1 \\2 \\ 3\end{bmatrix} \begin{bmatrix}3 \\ 3 \\ 3\end{bmatrix}\\ \begin{bmatrix}4 \\5 \\ 6\end{bmatrix}\end{aligned}ua(b−a)∗t123(567−123)∗0.75123444∗0.75123333456插值因子的变化物体的空间运动控制移动开关private float t 1.1f; public void BeginLerp() { t 0f; }固定时长平滑移动public float lerpTime 1f; private void FixedUpdate() { if (t 1f) { t Mathf.Clamp01(1f / lerpTime * Time.fixedDeltaTime); objectToLerp.transform.position Vector3.Lerp(objectToLerp.transform.position, destinationTransform.position, t); } }移动到目的地Color.Lerp在颜色结构中颜色由4个浮点表示分别代表红、蓝、绿和阿尔法。使用 Lerp 时每个浮点数会像对Mathf.Lerp一样进行插值。颜色渐变public Image background; public ListColor socials new ListColor(); public float frequency 3f; private float t 1.1f; public void BeginLerp() { t 0f; } private void Update() { if (t 1) { t Mathf.Sin(Time.time * frequency); background.color Color.Lerp(socials[0], socials[1], t); } }自定义要渐变的颜色