我有以下鼠标代码(带有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);
}
}
答案 0 :(得分:0)
我找到了您的答案,here 该页面包含一个名为mouselook的类,它是一种统一资产,您可以通过Unity Asset Demo Package免费获得。但是您可以根据需要在此处获取脚本。
有关您的工作方式...从编程的角度来看,将脚本放到使用transform.lookAt()
Vector3 point = new Vector3();
Event currentEvent = Event.current;
Vector2 mousePos = new Vector2();
// Get the mouse position from Event.
// Note that the y position from Event is inverted.
mousePos.x = currentEvent.mousePosition.x;
mousePos.y = cam.pixelHeight - currentEvent.mousePosition.y;
point = cam.ScreenToWorldPoint(new Vector3(mousePos.x, mousePos.y, cam.nearClipPlane));
transform.LookAt(point);
您可以将其放在相机上并旋转一下。重要的是要注意:
mousePos.y = cam.pixelHeight - currentEvent.mousePosition.y;
因为从屏幕上的点转换到您的世界中的某个点,并且鼠标y在屏幕上的位置反转,所以这会为您翻转。祝你好运。