Vector3.Lerp 错误?
Vector3.Lerp bug?
我知道如何随时间移动游戏对象,但我有一个奇怪的错误。
我正在尝试创建漂亮的动画,其中相机在单击按钮时向前移动,在第二次单击按钮时向后移动。
我正在使用 here 中的代码来制作动画,但遇到了一个奇怪的问题。
这是我的代码:
private float time = 5, current;
public void MoveBackward()
{
StartCotoutine(MoveTo(Vector3.zero));
}
public void MoveForward()
{
StartCotoutine(MoveTo(new Vector3(0,0,15)));
}
private IEnumerator MoveTo(Vector3 target)
{
current=0;
while(transform.position!=target)
{
transform.position = Vector3.Lerp(transform.position, target, current/time);
current = Mathf.Clamp(current+Time.deltaTime,0,time);
yield return null;
}
}
向前运动效果很好,但由于某种原因,当我尝试向后移动时,它移动得太快了。我尝试打印结果 (current/time),在向后移动中,当变换到达目的地时它是 0.1(大约)。
P.S。 - 我是 运行 另一个 Cotoutine
在后台(如果重要的话)
你知道为什么会这样吗?
提前致谢
问题在于你在这里调用 lerp 的方式:
transform.position = Vector3.Lerp(transform.position, target, current/time);
这将告诉它根据时间从 当前 位置 lerp 到结束,这将不是线性的。您需要存储起始位置并在所有 lerping 中使用它,以便获得正确的插值。
另外,根据 lerp 的完成方式,比较浮点值可能意味着这永远不会结束。最好通过比较 lerping 量来检查 lerping 是否完成。
我知道如何随时间移动游戏对象,但我有一个奇怪的错误。
我正在尝试创建漂亮的动画,其中相机在单击按钮时向前移动,在第二次单击按钮时向后移动。
我正在使用 here 中的代码来制作动画,但遇到了一个奇怪的问题。
这是我的代码:
private float time = 5, current;
public void MoveBackward()
{
StartCotoutine(MoveTo(Vector3.zero));
}
public void MoveForward()
{
StartCotoutine(MoveTo(new Vector3(0,0,15)));
}
private IEnumerator MoveTo(Vector3 target)
{
current=0;
while(transform.position!=target)
{
transform.position = Vector3.Lerp(transform.position, target, current/time);
current = Mathf.Clamp(current+Time.deltaTime,0,time);
yield return null;
}
}
向前运动效果很好,但由于某种原因,当我尝试向后移动时,它移动得太快了。我尝试打印结果 (current/time),在向后移动中,当变换到达目的地时它是 0.1(大约)。
P.S。 - 我是 运行 另一个 Cotoutine
在后台(如果重要的话)
你知道为什么会这样吗?
提前致谢
问题在于你在这里调用 lerp 的方式:
transform.position = Vector3.Lerp(transform.position, target, current/time);
这将告诉它根据时间从 当前 位置 lerp 到结束,这将不是线性的。您需要存储起始位置并在所有 lerping 中使用它,以便获得正确的插值。
另外,根据 lerp 的完成方式,比较浮点值可能意味着这永远不会结束。最好通过比较 lerping 量来检查 lerping 是否完成。