简体   繁体   中英

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

I have a main camera in Unity3D that I want to rotate depending on mouse input, so it works as a first person video-game where you move the mouse depending on where do you want to look at.

The starting values of the camera (Transform tab in Inspector tab in Unity) are:

  1. Position : X = -1, Y = 1, Z = -11.
  2. Rotation : X = 0, Y = 0, Z = 0.
  3. Scale : X = 1, Y = 1, Z = 1.

I added a Script component for the Main Camera. And it is the following 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);
          }
     }
}

However, when I play the scene the camera doesn't rotate like it should. The values of the rotation change in x-axis, y-axis and even for z-axis .

What am I doing wrong?

That's a problem with how Quaternion is calculated. This happens when multiple axis are being modified. If you comment all the x rotation or the y rotation, and only rotate in one axis at a time, you will realize that this problem will go away.

To properly rotate your camera with the mouse input, use the eulerAngles or localEulerAngles variables. The option between these two depends on what you are doing.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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