作为Ruzihm's answer 的替代方案,我想在这里留下一个实际使用Lerp 的解决方案。
这样做的巨大优势是您可以另外添加缓入和缓出,例如使用Mathf.SmoothStep 甚至使用其他数学计算来改变旋转的动画。
它还允许您准确控制旋转需要多长时间,而与必须旋转多少度无关。在下面的示例中,我再次使用您的速度值(以每秒度数为单位)计算了持续时间,但您也可以简单地例如通过固定的持续时间,例如 1 或 2 秒。
public class CameraMove : MonoBehaviour
{
public static bool start = false;
public Vector3 targetPosition;
// it's easier to adjust euler angles instead
public Vector3 targetRotation;
// here now set the rotation speed in degrees / second
public float speed = 90f;
void Start()
{
StartCoroutine(cameraRotate());
}
private IEnumerator cameraRotate()
{
// Trigger cameraMove until clicking the sphere
yield return new WaitUntil(() => start == true);
var startRotation = transform.localRotation;
var finalRotation = Quaternion.Euler(targetRotation);
// angle difference / angle per second => duration in seconds
var duration = Quaternion.Angle(startRotation, finalRotation) / speed;
var timePassed = 0f;
while (timPassed < duration)
{
// with this factor you get a linear rotation like using Quaternion.RotateTowards ...
var lerpFactor = timPassed / duration;
// ... Huge advantage: You can now add ease-in and ease-out to the rotation!
var smoothedLerpFactor = Mathf.SmoothStep(0, 1, lerpFactor);
transform.localRotation = Quaternion.Lerp(startRotation, finalRotation, smoothedLerpFactor);
// add to the timePassed avoiding overshooting
timaPassed += Mathf.Min(duration - timePassed, Time.deltaTime);
yield return null;
}
// to be sure set the rotation fixed when done
transform.localRotation = finalRotation;
}
}
更多关于缓动数学结账的精彩示例this post
例如因为我们有缓入和缓出:
var lerpFactor = passedTime / duration;
smoothedLerpFactor = Mathf.SmoothStep(0, 1, lerpFactor);
例如只是缓出
var lerpFactor = passedTime / duration;
smoothedLerpFactor = Mathf.Sin(lerpFactor * Mathf.PI * 0.5f);
例如只有缓入
var lerpFactor = passedTime / duration;
smoothedLerpFactor = 1f - Mathf.Cos(lerpFactor * Mathf.PI * 0.5f);
例如指数级的轻松
var lerpFactor = passedTime / duration;
smoothedLerpFactor = lerpFactor * lerpFactor;
您还可以多次使用它们来增加平滑效果,例如超级流畅的步骤;)
var lerpFactor = passedTime / duration;
smoothedLerpFactor = Mathf.SmoothStep(0, 1, Mathf.SmoothStep(0, 1, lerpFactor));