如何在垂直轴上夹紧旋转?

How to clamp rotation on a vertical axis?

我正在使用 Unity 中的 sketchfab 之类的对象查看器,目前正在使用鼠标进行相机旋转。到目前为止,一切似乎都正常,但我想将旋转夹在垂直轴上,但在实现这一点时遇到了一些麻烦。

这是我完成相机旋转的方式:

[SerializeField] Transform camPivot = null;
[SerializeField] float     speed    = 850.0F;

private Quaternion      _camRot         { get; set; } = Quaternion.identity;
private float           _polar          { get; set; } = 0;
private float           _elevation      { get; set; } = 0;

void DoRotation()
{
    this._polar     += Input.GetAxis("Mouse X") * this.speed * Mathf.Deg2Rad;
    this._elevation -= Input.GetAxis("Mouse Y") * this.speed * Mathf.Deg2Rad;

    this._camRot = Quaternion.AngleAxis(this._elevation, Vector3.right);
    this._camRot = Quaternion.AngleAxis(this._polar, Vector3.up) * this._camRot;
}
private void Update()
{
    this.DoRotation();

    this.camPivot.localRotation = Quaternion.Slerp(this.camPivot.localRotation, this._camRot, Time.unscaledDeltaTime * 5.0F);
}

此外,我想始终确保 z 旋转为零,因为我只需要水平和垂直旋转相机枢轴,我尝试将 camPivot euler z 值设置为 0,但它给了我一些非常奇怪的行为。

var euler = this.viewCamera.Pivot.eulerAngles; euler.z = 0.0f;
    this.viewCamera.Pivot.eulerAngles = euler;

一个非常简单的解决方案是使用 Mathf.Clamp_elevation 钳位到 ±90:

void DoRotation()
{
    this._polar     += Input.GetAxis("Mouse X") * this.speed * Mathf.Deg2Rad;
    this._elevation -= Input.GetAxis("Mouse Y") * this.speed * Mathf.Deg2Rad;
    this._elevation = Mathf.Clamp(this._elevation, -90f, 90f);

    this._camRot = Quaternion.AngleAxis(this._elevation, Vector3.right);
    this._camRot = Quaternion.AngleAxis(this._polar, Vector3.up) * this._camRot;
}