【问题标题】:Keep camera from rotating around relative z-axis防止相机围绕相对 z 轴旋转
【发布时间】:2021-10-25 09:12:57
【问题描述】:

我正在尝试创建模仿统一场景编辑器行为的相机移动,您可以在其中通过 2d 鼠标移动围绕场景执行球形旋转。到目前为止,在给定 x 或 y 移动的情况下,相机正在正确旋转,但是对角拖动会导致相机围绕其相对 z 轴旋转,直到它被锁定。我不能强迫相机相对于世界向上看原点,因为那样它就不能倒置旋转

这是我附加到相机的脚本

using UnityEngine;

public class MainCamera : MonoBehaviour
{
    Vector2 startingPosition;
    Vector2 mousePosition;
    Vector3 orthogonalCameraVector;
    float degreesPerUnitWidth = 180f / Screen.width;
    float degreesPerUnitHeight = 180f / Screen.height;
    float cameraRadius = 10;

    void Start()
    {
        transform.position = new Vector3(0, 0, -cameraRadius);
        transform.LookAt(Vector3.zero);
        orthogonalCameraVector = -Vector3.left;
    }

    void LateUpdate()
    {
        if (Input.GetMouseButtonDown(0))
        {
            mousePosition = Input.mousePosition;
        }

        if (Input.GetMouseButton(0))
        {
            var input = new Vector2(Input.mousePosition.x ,Input.mousePosition.y);

            startingPosition = mousePosition;
            var mouseDelta = startingPosition - input;

            var xzDegrees = -mouseDelta.y * degreesPerUnitHeight;
            var xzRotation = Quaternion.AngleAxis(xzDegrees, orthogonalCameraVector); // rotate about the relative x-z plane
            var yRotation = Quaternion.AngleAxis(-mouseDelta.x * degreesPerUnitWidth, Vector3.up); // rotate about the world y-axis
            var rotation = xzRotation * yRotation;
            orthogonalCameraVector = rotation * orthogonalCameraVector;
            transform.position = rotation * transform.position;
            transform.rotation = rotation * transform.rotation;
            mousePosition = Input.mousePosition;
        }
    }
}

【问题讨论】:

    标签: unity3d


    【解决方案1】:

    我意识到orthogonalCamerVector 只需要围绕 y 轴旋转,因为我想保持它与 xz 平面平行。然后,我在旋转transform 之前将此旋转应用于orthogonalCamerVector,因此它始终围绕固定平面旋转,因此它看起来像这样:

            var xzDegrees = -mouseDelta.y * degreesPerUnitHeight;
            var yRotation = Quaternion.AngleAxis(-mouseDelta.x * degreesPerUnitWidth, Vector3.up); // rotate about the world y-axis
            orthogonalCameraVector = yRotation * orthogonalCameraVector;
            var xzRotation = Quaternion.AngleAxis(xzDegrees, orthogonalCameraVector); // rotate about the relative x-z plane
            var rotation = xzRotation * yRotation;
            transform.position = rotation * transform.position;
            transform.rotation = rotation * transform.rotation;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-09-22
      • 2018-08-03
      • 2013-09-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多