在 Unity 中缓慢旋转角度

Slowly rotating towards angle in Unity

我正在使用 SteamVR,并且想根据控制器升高的高度旋转相机,我已经编写了将控制器高度发送到我的相机脚本上的方法的脚本。

当我执行以下操作时,旋转有效:

transform.Rotate(0, 0, 30); // 30 is just to test, we will use the controller height later

但我想慢慢地做这个旋转,这不能立即发生。

我也尝试过使用 Quaternion.Lerp,但它似乎不起作用。

Quaternion.Lerp(this.transform.rotation, new Quaternion(this.transform.rotation.eulerAngles.x, this.transform.rotation.eulerAngles.y, zPosition, 0), Time.deltaTime * 5);

有什么建议吗?

如果其他人遇到此问题,我使用以下代码让我的工作正常进行:

Vector3 direction = new Vector3(transform.rotation.eulerAngles.x, transform.rotation.eulerAngles.y, -30);
Quaternion targetRotation = Quaternion.Euler(direction);
this.transform.rotation = Quaternion.Lerp(this.transform.rotation, targetRotation, Time.deltaTime * 1);

Quaternion.Lerp() 应该可以很好地满足您的需求 - 但是,您对它的使用会为该方法提供一些不正确的参数,这就是它没有按预期工作的原因。 (此外,您可能不应该使用它的构造函数来构造四元数,有一些辅助方法可以正确地从欧拉角转换。)

你需要做的是记录初始开始和结束旋转,并在每次调用时将它们传递给Quaternion.Lerp()。请注意,您不能只在每一帧引用 transform.rotation,因为它会随着对象的旋转而变化。例如,调整您的代码以使其工作:

Quaternion startRotation;
Quaternion endRotation;
float rotationProgress = -1;

// Call this to start the rotation
void StartRotating(float zPosition){

    // Here we cache the starting and target rotations
    startRotation = transform.rotation;
    endRotation = Quaternion.Euler(transform.rotation.eulerAngles.x, transform.rotation.eulerAngles.y, zPosition);

    // This starts the rotation, but you can use a boolean flag if it's clearer for you
    rotationProgress = 0;
}

void Update() {
    if (rotationProgress < 1 && rotationProgress >= 0){
        rotationProgress += Time.deltaTime * 5;

        // Here we assign the interpolated rotation to transform.rotation
        // It will range from startRotation (rotationProgress == 0) to endRotation (rotationProgress >= 1)
        transform.rotation = Quaternion.Lerp(startRotation, endRotation, rotationProgress);
    }
}

希望对您有所帮助!如果您有任何问题,请告诉我。