统一夹住四元数旋转

Clamp a quaternion rotation in unity

我有这段代码,但我无法找到一个合适的解决方案来将 X 轴夹在两个角度值之间。在这种情况下会怎么做?

public class CameraController : MonoBehaviour {
    public float cameraSmoothness = 5f;

    private Quaternion targetGlobalRotation;
    private Quaternion targetLocalRotation = Quaternion.Identity;

    private void Start(){
        targetGlobalRotation = transform.rotation;
    }

    private void Update(){
        targetGlobalRotation *= Quaternion.Euler(
            Vector3.up * Input.GetAxis("Mouse X"));
        
        targetLocalRotation *= Quaternion.Euler(
            Vector3.right * -Input.GetAxis("Mouse Y"));

        transform.rotation = Quaternion.Lerp(
            transform.rotation,
            targetGlobalRotation * targetLocalRotation,
            cameraSmoothness * Time.deltaTime);
    }
}

为此,您宁愿使用欧拉角,并且仅在应用夹具后将它们转换为 Quaternion

切勿 直接触摸 Quaternion 的各个组件,除非您真的很清楚自己在做什么!一个 Quaternion四个 个分量 xyzw,它们都在范围 -11 所以你的尝试毫无意义 ;)

它可能类似于

// Adjust via Inspector
public float minXRotation = 10;
public float maxXRotation = 90;

// Also adjust via Inspector
public Vector2 sensitivity = Vector2.one;

private float targetYRotation;
private float targetXRotation;

private void Update()
{
    targetYRotation += Input.GetAxis("Mouse X")) * sensitivity.x;      
    targetXRotation -= Input.GetAxis("Mouse Y")) * sensitivity.y;

    targetXRotation = Mathf.Clamp(targetXRotation, minXRotation, maxXRotation);

    var targetRotation = Quaternion.Euler(Vector3.up * targetYRotation) * Quaternion.Euler(Vector3.right * targetXRotation);

    transform.rotation = Quaternion.Lerp(transform.rotation, targetRotation, cameraSmoothness * Time.deltaTime);
}