一、介绍
插值函数(Lerp和Slerp)是 Unity 中的两个常用函数,用于在两个数值之间进行插值运算。它们的作用是在两个值之间进行插值,返回一个介于这两个值之间的数值。Lerp 函数的全称是 Linear Interpolation,也就是线性插值,而Slerp 函数的全称是 Spherical linear interpolation,也就是球面线性插值。
在游戏开发中,Lerphe 函数常用于实现平滑的移动、旋转和缩放等效果,可以让物体的运动更加真实和平滑。
二、方法
1.Lerp方法
Lerp 函数的定义如下:
public static float Lerp(float a, float b, float t);
public static Vector3 Lerp(Vector3 a, Vector3 b, float t);
public static Quaternion Lerp(Quaternion a, Quaternion b, float t);
Lerp 函数有三种重载形式,分别用于对 float、Vector3 和 Quaternion 类型的数值进行插值。
第一个参数 a 表示起始值,第二个参数 b 表示结束值。
第三个参数 t 表示插值的权重,取值范围为 [0, 1],表示插值在起始值和结束值之间的权重,当 t=0 时返回起始值 a,当 t=1 时返回结束值 b,当 t=0.5 时返回 a 和 b 的平均值。
2.常见例子
(1)在Update或FixedUpdate里面实现平滑移动
public float speed = 5f;
public Transform target;
void Update()
{
transform.position = Vector3.Lerp(transform.position, target.position, speed * Time.deltaTime);
}
这段代码实现了一个平滑的移动效果,让物体向目标位置移动。在 Update 函数中,使用 Lerp 函数对当前位置和目标位置进行插值,返回一个新的位置,然后将物体移动到该位置。其中 speed 参数控制了插值的速度,可以通过调整该参数来控制物体的移动速度。
(2)在Update或FixedUpdate里面实现平滑旋转
public float speed = 5f;
public Transform target;
void Update()
{
transform.rotation = Quaternion.Lerp(transform.rotation, target.rotation, speed * Time.deltaTime);
}
这段代码实现了一个平滑的旋转效果,让物体向目标方向旋转。在 Update 函数中,使用 Lerp 函数对当前旋转角度和目标旋转角度进行插值,返回一个新的旋转角度,然后将物体旋转到该角度。其中 speed 参数控制了插值的速度,可以通过调整该参数来控制物体的旋转速度。
(3)在协程里面实现平滑移动或旋转
IEnumerator Move(Vector3 StartPos, Vector3 target, float NeedTime)
{
float time = 0f;
while (time < NeedTime)
{
transform.position= Vector3.Lerp(StartPos,target,time/NeedTime);
time += Time.deltaTime;
yield return null;
}
transform.position =target;
}
这段代码实现了一个平滑的移动效果,让物体向目标位置移动。在 协程中,使用 Lerp 函数对当前位置和目标位置进行插值,返回一个新的位置,然后将物体移动到该位置,会比在Update及FixedUpdate内使用会更加平滑,通过yield return null返回一帧给主线程,通过while循环调用进行移动,旋转同理。
(4)在Update或FixedUpdate里面实现颜色来回渐变
public float speed = 5f;
public Renderer renderer;
public Color startColor;
public Color endColor;
void Update()
{
float t = Mathf.PingPong(Time.time * speed, 1f);
renderer.material.color = Color.Lerp(startColor, endColor, t);
}
这段代码实现了一个颜色渐变效果,让物体的颜色在起始颜色和结束颜色之间进行渐变。在 Update 函数中,使用 Lerp 函数对起始颜色和结束颜色进行插值,返回一个新的颜色,然后将物体的颜色设置为该颜色。其中 speed 参数控制了插值的速度,可以通过调整该参数来控制颜色的渐变速度。通过 Mathf.PingPong 函数,可以让 t 值在 [0, 1] 范围内循环变化,从而实现来回渐变的效果。
(未完待续.........)