这不起作用的原因是您没有正确使用 Lerp。这就是线性插值 (Lerp) 的数学原理:
假设我们有一个点 (0, 0) 和一个点 (1, 1)。为了在点之间进行计算,我们提供了一个从0.0f 到1.0f 的t 值。这个t 表示两点之间的比率(0.0f 是(0, 0) 和1.0f 是(1, 1))。例如,0.5f 的 t 值将导致点 (0.5f, 0.5f)。
现在用一个不那么琐碎的例子对此进行扩展,请考虑两点:
var a = Vector2(1.0f, -1.0f) 和 var b = Vector2(0.0f, 1.0f)。 Lerp(a, b, 0.5f) 的结果是 Vector2(0.5f, 0.0f),因为这是中间点。让我们将答案称为c。给我们答案的方程式是c = a + (0.5f * (b - a))。这来自对线性代数的基本理解,其中两个点相减得到一个向量,将一个向量添加到一个点得到另一个点。
好的,现在开始让这段代码真正按照您想要的方式工作。您的脚本可能如下所示:
float moveTime = 10.0f; // In seconds
float moveTimer = 0.0f; // Used for keeping track of time
bool moving = false; // Flag letting us know if we're moving
float heightChange = 10.0f; // This is the delta
// These will be assigned when a collision occurs
Vector3 target; // our target position
Vector3 startPos; // our starting position
void OnTriggerEnter2D(Collider2D other)
{
if (!moving)
{
// We set the target to be ten units above our current position
target = transform.position + Vector3.up * heightChange;
// And save our start position (because our actual position will be changing)
startPos = transform.position;
// Set the flag so that the movement starts
moving = true;
}
}
void Update()
{
// If we're currently moving and the movement hasn't finished
if (moving && moveTimer < moveTime)
{
// Accumulate the frame time, making the timer tick up
moveTimer += Time.deltaTime;
// calculate our ratio ("t")
float t = moveTimer / moveTime;
transform.position = Vector3.Lerp(startPos, target, t);
}
else
{
// We either haven't started moving, or have finished moving
}
}
希望这会有所帮助!