在Unity

时间:2017-03-07 20:46:25

标签: c# unity3d quaternions virtual-reality

我正在使用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);

有什么建议吗?

2 个答案:

答案 0 :(得分:4)

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

您需要做的是记录初始开始和结束轮换,并在每次调用时将它们传递到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);
    }
}

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

答案 1 :(得分:3)

如果有其他人遇到这个,我使用以下代码让我的工作:

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);