Unity运行时鼠标视角上下反转问题求助(附代码)
问题修复:Unity鼠标上下视角反转
问题根源在于PlayerLook脚本中xRotation的计算逻辑,直接累加鼠标Y轴输入会导致视角反转,只需将加法改为减法即可解决。
修改核心代码行
在ProcessLook方法中,将:
xRotation += (mouseY * Time.deltaTime) * ySensetivity;
替换为:
xRotation -= (mouseY * Time.deltaTime) * ySensetivity;
修改后的完整PlayerLook代码
using System.Collections; using System.Collections.Generic; using UnityEngine; public class PlayerLook : MonoBehaviour { public Camera cam; private float xRotation = 0f; public float xSensitivity = 30f; public float ySensetivity = 30f; public void ProcessLook(Vector2 input) { float mouseX = input.x; float mouseY = input.y; // 修正视角反转问题:将加法改为减法 xRotation -= (mouseY * Time.deltaTime) * ySensetivity; xRotation = Mathf.Clamp(xRotation, -80f, 80f); cam.transform.localRotation = Quaternion.Euler(xRotation, 0, 0); transform.Rotate(Vector3.up * (mouseX * Time.deltaTime) * xSensitivity); } }
原理说明
Unity新输入系统的Mouse Y轴输入默认规则是:
- 向下拖动鼠标 → 返回正值
- 向上拖动鼠标 → 返回负值
原代码中累加这个值会导致:向下拖鼠标时xRotation增大,相机向上旋转(和预期相反);改为减法后,向下拖鼠标时xRotation减小,相机向下旋转,符合正常操作直觉。
内容的提问来源于stack exchange,提问作者оказывается
相关产品推荐
相关产品推荐

