Unity3D FPS开发:相机垂直旋转FOV拉伸及移动问题求助
Unity FPS 相机与移动问题解决方案
问题根源分析
- MouseAiming函数问题:旋转Player的X/Y轴导致Player自身朝向包含垂直分量,移动时
transform.forward指向斜上方,触发“抬头前进飞起来”的现象。 - MouseAiming2函数问题:大概率是将垂直旋转错误应用到了Player或相机的非正确轴上,或枪支作为相机子物体的位置/缩放设置不当,导致视觉上的FOV畸变。
正确实现方案
1. 明确旋转职责分工
Player仅负责水平旋转(Y轴,左右转向),PlayerCam负责垂直旋转(X轴,上下抬头),彻底分离旋转逻辑,避免Player朝向偏离水平面。
2. 修正后的核心代码示例
public class PlayerController : MonoBehaviour { public float mouseSensitivity = 100f; public float moveSpeed = 5f; public Transform playerCam; // 拖拽赋值PlayerCam private float _xRotation = 0f; void Start() { Cursor.lockState = CursorLockMode.Locked; } void Update() { // 读取鼠标输入 float mouseX = Input.GetAxis("Mouse X") * mouseSensitivity * Time.deltaTime; float mouseY = Input.GetAxis("Mouse Y") * mouseSensitivity * Time.deltaTime; // Player仅绕Y轴旋转(左右转向) transform.Rotate(Vector3.up * mouseX); // 相机绕X轴旋转上下视角,限制角度防止翻转 _xRotation -= mouseY; _xRotation = Mathf.Clamp(_xRotation, -89f, 89f); playerCam.localRotation = Quaternion.Euler(_xRotation, 0f, 0f); // 移动逻辑:确保方向始终在水平面 float horizontal = Input.GetAxis("Horizontal"); float vertical = Input.GetAxis("Vertical"); Vector3 moveDir = transform.right * horizontal + transform.forward * vertical; // 将移动方向投影到水平面,消除垂直分量 moveDir = Vector3.ProjectOnPlane(moveDir, Vector3.up).normalized; transform.Translate(moveDir * moveSpeed * Time.deltaTime, Space.World); } }
3. FOV畸变问题排查与修复
- 检查相机设置:确保相机的
Field of View值未被代码意外修改,近裁剪面设置为合理值(如0.1),避免模型被过度裁剪。 - 枪支子物体设置:枪支与BulletSpawnPoint作为PlayerCam的子物体,需固定其
localPosition和localRotation,不要随相机旋转额外调整,防止视觉上的缩放/偏移错觉。 - 避免错误旋转方式:不要使用
eulerAngles直接修改相机旋转,改用localRotation配合Quaternion.Euler,避免角度累积导致的异常。
内容的提问来源于stack exchange,提问作者Thill020
相关产品推荐
相关产品推荐

