首页 > 解决方案 > Quaternion.Slerp 由于某种原因旋转不顺畅

问题描述

我正在尝试用 Unity 使像物体一样的摇摆不定的物体旋转,并且由于某种原因,旋转是即时的,而不是逐渐的运动。我之前曾研究过 Slerp 和 Lerp,但我无法让它与任何一个一起工作。我想知道是否有人有任何见解,因为我确定我错过了一些愚蠢而简单的 xD。谢谢!这是方法。

private void Rotate(float rotateAmount)
    {
        var oldRotation = transform.rotation;
        transform.Rotate(0, 0, rotateAmount);
        var newRotation = transform.rotation;
 
        for (float t = 0; t <= 1.0; t += Time.deltaTime)
        {
            transform.rotation = Quaternion.Slerp(oldRotation, newRotation, t);
        }
        transform.rotation = newRotation;
    }
}

标签: c#unity3d

解决方案


循环中完成的所有旋转for都发生在帧下。您看不到它们在一帧下的变化。使该Rotate函数成为协程函数,然后在每个循环中等待一帧,yield return null您应该会看到随时间的变化。

private IEnumerator Rotate(float rotateAmount)
{
    var oldRotation = transform.rotation;
    transform.Rotate(0, 0, rotateAmount);
    var newRotation = transform.rotation;

    for (float t = 0; t <= 1.0; t += Time.deltaTime)
    {
        transform.rotation = Quaternion.Slerp(oldRotation, newRotation, t);
        yield return null;
    }
    transform.rotation = newRotation;
}

因为它是一个协程函数,所以你启动它而不是直接调用它:

StartCoroutine(Rotate(90f));

我注意到你曾经transform.Rotate(0, 0, rotateAmount)得到目标角度。你不需要这样做。如果您需要将对象从当前角度旋转到另一个角度,请获取当前角度,然后将其添加到目标角度并用于Vector3.Lerplerp 旋转。

请参阅这篇文章中的“随时间推移的增量角旋转:”部分。


推荐阅读