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

Why is a camera rotated around z-axis in Unity3D?

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

摄像机的起始值(Unity Inspector 选项卡中的 Transform 选项卡)为:

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

我为主相机添加了一个脚本组件。并且是下面的class:

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 left
               transform.Rotate (new Vector3 (0f, -deltaRotation, 0f) * Time.deltaTime);
          }
          else 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 left
               transform.Rotate (new Vector3 (deltaRotation, 0f, 0f) * Time.deltaTime);
          }
          else if(Input.GetAxis("Mouse Y") > 0){
          //Code for action on mouse moving right
               transform.Rotate (new Vector3 (-deltaRotation, 0f, 0f) * Time.deltaTime);
          }
     }
}

但是,当我播放场景时,相机没有按应有的方式旋转。 rotation 的值在 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);
}