[英]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.我在 Unity3D 中有一个主摄像头,我想根据鼠标输入进行旋转,因此它可以作为第一人称视频游戏使用,您可以根据要查看的位置移动鼠标。
The starting values of the camera (Transform tab in Inspector tab in Unity) are:相机的起始值(Unity Inspector 选项卡中的 Transform 选项卡)是:
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 .旋转值在 x 轴、y 轴甚至z 轴上发生变化。
What am I doing wrong?我究竟做错了什么?
That's a problem with how Quaternion
is calculated.这是Quaternion
计算方式的问题。 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.如果你注释掉所有的 x 旋转或 y 旋转,并且一次只在一个轴上旋转,你就会意识到这个问题会消失。
To properly rotate your camera with the mouse input, use the eulerAngles
or localEulerAngles
variables.要使用鼠标输入正确旋转相机,请使用eulerAngles
或localEulerAngles
变量。 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);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.