【发布时间】:2018-09-22 11:54:27
【问题描述】:
我有以下鼠标代码(带有 Unity 的 C#)用鼠标(x、y 和 z)旋转相机。但是当我用鼠标旋转相机时,相机会移动一个偏移量。
void Update()
{
Turn();
Thrust();
}
void Turn()
{
float yaw = turnSpeed * Time.deltaTime * Input.GetAxis("Mouse X"); //Horizontal
float pitch = turnSpeed * Time.deltaTime * Input.GetAxis("Mouse Y"); //Pitch
float roll = turnSpeed * Time.deltaTime * Input.GetAxis("Roll") //Roll
transform.Rotate(-pitch, yaw, -roll)
}
我希望相机完全随着鼠标的移动而移动(就像 FPS 一样)。这段代码有什么问题?
编辑
从副本中尝试了解决方案。当我在 x 轴上将相机旋转超过 +/- 180 度时,我遇到了万向节锁定问题(左变为右,右变为左)。
public class Movement002 : MonoBehaviour {
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;
Transform player;
void Start()
{
player = this.transform.parent.transform;
}
// 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);
//xRotCounter = xRotCounter % 360;//Optional
player.localEulerAngles = new Vector3(-yRotCounter, xRotCounter, 0);
}
}
【问题讨论】:
-
使用
transform.localEulerAngles比使用transform.Rotate更有意义,比如鼠标控制。 -
它带来了一个新问题:云台锁。另请参阅我关于 Unity 中的 Gimbal Lock 的其他问题 stackoverflow.com/questions/52347474/…
-
请注意,您没有使用我提到的
transform.localEulerAngles。您使用了transform.rotation,它们不是一回事。使用来自duplicate 的代码。这是一个 FPS 代码,没有云台锁定问题 -
好的,此代码是否也可用于 6DOF 游戏(x、y 和 z 轴上的 360 度)?
-
我不知道。此问题已被标记为重复,您必须自己尝试重复。如果不尝试,您将不知道它是否有效。我注意到您也在使用
z轴,您可能想要将new Vector3(-yRotCounter, xRotCounter, 0);更改为new Vector3(-yRotCounter, xRotCounter, roll);。它在y轴上也有角度限制,但如果您不想要它,只需删除yRotCounter = Mathf.Clamp(yRotCounter, yMinLimit, yMaxLimit);.而已。编码愉快!