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

问题描述 投票:0回答:1

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

enter image description here

c# unity3d rotation quaternions euler-angles
1个回答
1
投票

一个非常简单的解决方案是使用_elevationMathf.Clamp钳位到±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;
}
最新问题
© www.soinside.com 2019 - 2024. All rights reserved.