首页 > 解决方案 > 如何限制 Quaternion.Slerp() 函数的旋转

问题描述

我一直在做一个 VR 项目,其中一双眼睛跟踪世界空间中的一个点。对于初学者,我使用玩家的控制器作为目标。眼睛目前完全按照我的预期跟踪,但是由于它们是眼睛,我想限制它们可以向上/向下和向左/向右看的距离。我曾尝试使用 localEulerAngles 来完成此操作,这似乎可行,但是一旦我输入“错误” if block,眼睛旋转就不会再改变,因此会卡住。所以我认为我需要强制旋转回到可接受的限制,但我不知道如何正确地做到这一点。我还认为可能有更好的方法来完成我不知道的整件事。这是我当前的更新功能:

    void Update(){

    Vector3 direction = finger.position - this.transform.position;

    float angleX = transform.localEulerAngles.x;

    //this text is displayed in VR so that I can see while I test
    temp.text = transform.localEulerAngles.x.ToString();

    //this condition is for if the finger is held up in the air
    if (pointing)
    {
        //because of the way angles work, it is necessary to check what      CANT be?. 
        if (angleX > 15 && angleX < 350)
        {
            //what to do here?

        }
        else
        {
            //look at the finger
            this.transform.rotation = Quaternion.Slerp(this.transform.rotation, Quaternion.LookRotation(direction), 0.1f);
        }

    } 
}

标签: c#unity3dquaternions

解决方案


使用该Mathf.Clamp方法将浮点值限制在最小值和最大值之间,然后将变换的 X 角度重置为钳制值。

所以你的Update方法变成:

void Update() {

    Vector3 direction = finger.position - this.transform.position;

    float angleX = transform.localEulerAngles.x;

    //this text is displayed in VR so that I can see while I test
    temp.text = transform.localEulerAngles.x.ToString();

    //this condition is for if the finger is held up in the air
    if (pointing)
    {
        float clampedAngle = Mathf.Clamp(angleX, 15f, 350f);
        transform.localEulerAngles.x = clampedAngle;

        //look at the finger
        this.transform.rotation = Quaternion.Slerp(this.transform.rotation, Quaternion.LookRotation(direction), 0.1f);
    }
} 

推荐阅读