繁体   English   中英

为什么在 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。

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

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);
          }
     }
}

但是,当我播放场景时,相机不会像它应该的那样旋转。 旋转值在 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);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM