为什么相机在Unity3D中围绕z轴旋转?

我在Unity3D中有一个主摄像头 ,我想根据鼠标输入进行旋转,因此它可以作为第一人称video游戏,根据您想要查看的位置移动鼠标。

摄像机的起始值(Unity中的“检查器”选项卡中的“变换”选项卡)为:

  1. 位置 :X = -1,Y = 1,Z = -11。
  2. 旋转 :X = 0,Y = 0,Z = 0。
  3. 比例 :X = 1,Y = 1,Z = 1。

我为主摄像头添加了一个脚本组件。 它是以下类:

using UnityEngine; using System.Collections; public class CameraMove : MonoBehaviour { float deltaRotation = 50f; // Use this for initialization void Start () { } // Update is called once per frame void Update () { if(Input.GetAxis("Mouse X")  0){ //Code for action on mouse moving right transform.Rotate (new Vector3 (0f, deltaRotation, 0f) * Time.deltaTime); } if(Input.GetAxis("Mouse Y")  0){ //Code for action on mouse moving right transform.Rotate (new Vector3 (-deltaRotation, 0f, 0f) * Time.deltaTime); } } } 

但是,当我播放场景时,相机不会像它应该的那样旋转。 旋转值在x轴,y轴和偶数z轴上变化

我究竟做错了什么?

这是Quaternion如何计算的问题。 当修改多个轴时会发生这种情况。 如果您对所有x旋转或y旋转进行注释,并且一次仅在一个轴上旋转,您将意识到此问题将消失。

要使用鼠标输入正确旋转相机,请使用eulerAngleslocalEulerAngles变量。 这两者之间的选择取决于你在做什么。

 public float xMoveThreshold = 1000.0f; public float yMoveThreshold = 1000.0f; public float yMaxLimit = 45.0f; public float yMinLimit = -45.0f; float yRotCounter = 0.0f; float xRotCounter = 0.0f; // Update is called once per frame void Update() { xRotCounter += Input.GetAxis("Mouse X") * xMoveThreshold * Time.deltaTime; yRotCounter += Input.GetAxis("Mouse Y") * yMoveThreshold * Time.deltaTime; yRotCounter = Mathf.Clamp(yRotCounter, yMinLimit, yMaxLimit); transform.localEulerAngles = new Vector3(-yRotCounter, xRotCounter, 0); }