lerpf
2026/4/14大约 2 分钟
最后同步日期:2026-04-15 | Godot 官方原文 — lerpf
lerpf
定义
lerpf() 是"线性插值"(Linear Interpolation)的浮点版本。它的作用是:在两个数值之间,按照给定的比例,算出中间的值。
想象你在一条 0 到 100 的路线上行走,weight(权重)就是你的进度百分比。weight = 0.0 时你在起点,weight = 1.0 时你在终点,weight = 0.5 时你正好在中间。所以 lerpf(0, 100, 0.5) 返回 50。
这个函数在游戏开发中极为常用——平滑移动、渐变透明度、颜色过渡等动画效果都离不开它。
函数签名
C#
public static float Lerp(float from, float to, float weight)GDScript
func lerpf(from: float, to: float, weight: float) -> float参数说明
| 参数 | 类型 | 必需 | 说明 |
|---|---|---|---|
from | float | 是 | 起始值(权重为 0 时的值) |
to | float | 是 | 目标值(权重为 1 时的值) |
weight | float | 是 | 插值权重,0.0 返回 from,1.0 返回 to,0.5 返回中间值 |
返回值
float —— 计算公式为 from + (to - from) * weight。
代码示例
C#
// 基本用法:在 0 和 100 之间取中间值
float mid = Mathf.Lerp(0f, 100f, 0.5f); // 50
// 平滑移动角色
public override void _Process(double delta)
{
// 每帧向目标位置靠近 10%
Position = Position.Lerp(_targetPosition, 0.1f);
}
// 渐变透明度:从完全透明到完全不透明
float alpha = Mathf.Lerp(0f, 1f, 0.3f); // 0.3GDScript
# 基本用法:在 0 和 100 之间取中间值
var mid = lerpf(0.0, 100.0, 0.5) # 50.0
# 平滑移动角色
func _process(delta):
# 每帧向目标位置靠近 10%
position = position.lerp(target_position, 0.1)
# 渐变透明度:从完全透明到完全不透明
var alpha = lerpf(0.0, 1.0, 0.3) # 0.3注意事项
weight的值不限于 0~1。超出这个范围时,结果会越过起点或终点。例如lerpf(0, 100, 1.5)返回150。- 如果你需要
weight严格限制在 0~1 之间,请在外层套用clampf()。 lerpf()是lerp()的纯浮点版本。lerp()可以处理 Vector2、Color 等类型,而lerpf()只处理单个浮点数。- C# 中使用
Mathf.Lerp(),功能完全一致。
