[英]Why is a camera rotated around z-axis in Unity3D?
我在 Unity3D 中有一個主攝像頭,我想根據鼠標輸入進行旋轉,因此它可以作為第一人稱視頻游戲使用,您可以根據要查看的位置移動鼠標。
相機的起始值(Unity Inspector 選項卡中的 Transform 選項卡)是:
我為主攝像頭添加了一個腳本組件。 它是以下類:
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 旋轉,並且一次只在一個軸上旋轉,你就會意識到這個問題會消失。
要使用鼠標輸入正確旋轉相機,請使用eulerAngles
或localEulerAngles
變量。 這兩者之間的選擇取決於你在做什么。
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.