Unity 6.6 Camera Movement 左右视角失效修复
数据小陈
左右旋转失效时,先别急着怀疑 mouseX。更常见的原因是旋转没有落到最终相机上。一般有三种情况:playerBody 拖成了 Camera 自身,transform.localRotation = Quaternion.Euler(xRotation, 0f, 0f); 每帧把水平旋转清零;playerBody 没赋值,playerBody.Rotate 报 NullReferenceException;Camera 不是 Player 根节点的子物体,Player 转了但相机没跟。先按下面的层级和引用检查,通常就能恢复左右视角。
1. 检查层级和 playerBody 引用
正确结构应当是:
Player (CharacterController)
└─ Camera (PlayerLook)
PlayerLook 挂在 Camera 上,playerBody 拖 Player 根节点,不要拖 Camera 自己,也不要留空。若 playerBody == transform,代码会先写 pitch,再给同一个 Transform 追加 yaw,但下一帧又执行:
transform.localRotation = Quaternion.Euler(xRotation, 0f, 0f);
这会把 yaw 重新置 0,表现就是只能上下看。
2. 检查 Look 输入是否真的读到了 X
打开 Input Actions 资产,确认 Look 是 Value、Control Type 为 Vector2,绑定为 <Mouse>/delta,不要只绑定 Y 轴,也不要把它做成只含上下方向的动作。可以临时在 HandleLook 里打印一次:
Debug.Log(lookInput);
左右移动鼠标时,如果 x 一直是 0,问题就在输入绑定;如果 x 有变化,问题在 Transform 层级或引用。
3. 修正后的关键代码
保留原脚本结构,重点加引用检查和正确的 yaw 旋转:
using UnityEngine;
using UnityEngine.InputSystem;
public class PlayerLook : MonoBehaviour
{
[Header("Look Settings")]
public float sensitivity = 2f;
public Transform playerBody; // 指向 Player 根节点,不是 Camera
private Player_Controls controls;
private Vector2 lookInput;
private float xRotation = 0f;
void Awake()
{
controls = new Player_Controls();
controls.Player.Look.performed += ctx => lookInput = ctx.ReadValue<Vector2>();
controls.Player.Look.canceled += ctx => lookInput = Vector2.zero;
}
void OnEnable()
{
controls.Enable();
Cursor.lockState = CursorLockMode.Locked;
Cursor.visible = false;
}
void OnDisable() => controls.Disable();
void Update()
{
HandleLook();
}
void HandleLook()
{
if (playerBody == null || playerBody == transform)
{
Debug.LogError("playerBody 应指向 Player 根节点,Camera 应作为 Player 的子物体");
return;
}
float mouseX = lookInput.x * sensitivity * Time.deltaTime;
float mouseY = lookInput.y * sensitivity * Time.deltaTime;
xRotation -= mouseY;
xRotation = Mathf.Clamp(xRotation, -90f, 90f);
transform.localRotation = Quaternion.Euler(xRotation, 0f, 0f);
playerBody.Rotate(0f, mouseX, 0f, Space.World);
}
}
注意事项
- 不要让 Camera 自己既做 pitch 又做 yaw,再被
Quaternion.Euler(xRotation, 0f, 0f)覆盖;典型做法是 Player 根节点负责 yaw,Camera 本地只负责 pitch。 - 如果
playerBody留空,playerBody.Rotate会抛异常,但 pitch 在它之前已经执行,所以表面上看就是“上下能动、左右不动”,记得看 Console。 - Input System 的鼠标 delta 本身已经是每帧变化量,乘
Time.deltaTime不是左右失效的直接原因,但会影响灵敏度手感;调手感时可单独调整sensitivity或去掉Time.deltaTime后重新测试。 - 若仍无效,先确认
controls.Enable()已执行、Cursor 已锁定,再用Debug.Log(lookInput.x)验证 X 输入。
备注:内容仅供参考。
