Unity Mathf.Lerp 使用详解:匀速、递减与曲线插值三种方式

参数解析

1
Mathf.Lerp(float a, float b, float t)
参数类型说明
afloat起始值
bfloat目标值
tfloat插值系数,自动夹紧到 [0, 1]

返回值:返回一个 float,表示从 ab 之间按 t 线性插值的结果。

计算公式result = a + (b - a) * t

  • t = 0 时,返回 a
  • t = 1 时,返回 b
  • t = 0.5 时,返回 ab 的中点

注意:t 会被自动夹紧到 [0, 1] 范围,传入超出范围的值不会产生外插效果。


使用方式

1. 匀速插值

在固定时间内从起始值线性过渡到目标值,t 随时间均匀增长。

1
2
3
4
5
6
7
8
9
10
11
12
13
public float duration = 3.0f;   // 插值持续时间(秒)
public float elapsed; // 已经过的时间

public void Update()
{
if (elapsed < duration)
{
elapsed += Time.deltaTime;

// 匀速从 0 插值到 100,elapsed/duration 作为进度百分比
float value = Mathf.Lerp(0f, 100f, elapsed / duration);
}
}

2. 递减插值(平滑阻尼效果)

每帧将当前值向目标值靠近固定比例,越接近目标值移动越慢,产生缓动效果。

1
2
3
4
5
6
7
8
9
10
public float curValue;          // 当前值
public float targetValue = 100f;
public float smoothFactor = 0.1f; // 每帧靠近目标的比例

public void Update()
{
// 每帧将 curValue 向 targetValue 靠近 10%
// 由于起始值不断更新,移动速度会逐渐减慢(非线性缓动)
curValue = Mathf.Lerp(curValue, targetValue, smoothFactor);
}

⚠️ 此方式的缓动速度与帧率相关,若需帧率无关的平滑效果,建议将 smoothFactor 替换为 1 - Mathf.Pow(0.1f, Time.deltaTime)

3. 曲线插值

结合 AnimationCurve 控制插值节奏,可实现加速、减速、弹性等非线性效果。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public float duration = 3.0f;
public float elapsed;
public AnimationCurve curve; // 在 Inspector 中配置运动曲线

public void Update()
{
if (elapsed < duration)
{
elapsed += Time.deltaTime;

float t = elapsed / duration;

// 用曲线对 t 进行重映射,实现非线性插值效果
float value = Mathf.Lerp(0f, 100f, curve.Evaluate(t));
}
}

注意事项

  • Mathf.Lerp 只接受 3 个参数,不存在 4 参数重载。
  • 若需要对向量进行插值,应使用 Vector3.LerpVector2.Lerp
  • 若需要对颜色进行插值,应使用 Color.Lerp
  • 若需要对四元数(旋转)进行插值,应使用 Quaternion.LerpQuaternion.Slerp
查看评论