Unity New Input System:旋转相机时玩家旋转不同步且移动方向异常求助
Unity新输入系统角色控制器:相机旋转同步与移动方向修复
问题核心
- 相机旋转时玩家对象旋转速度不同步:
PlayerLook中相机与角色的旋转逻辑不统一,未做帧率同步处理,导致两者旋转速度脱节。 - 移动方向与相机朝向不符:移动逻辑未基于相机当前朝向计算,W键触发的是角色自身前方移动,而非相机视角前方。
修复代码
1. 修正PlayerLook.cs(同步相机与角色旋转)
using UnityEngine; public class PlayerLook : MonoBehaviour { public Camera cam; private float xRotation = 0f; private float yRotation = 0f; // 建议设置为100左右,因加入了Time.deltaTime做帧率适配 public float xSensitivity = 100f; public float ySensitivity = 100f; public void ProcessLook(Vector2 input) { // 用Time.deltaTime保证不同帧率下旋转速度一致 float mouseX = input.x * Time.deltaTime * xSensitivity; float mouseY = input.y * Time.deltaTime * ySensitivity; xRotation -= mouseY; // 限制相机上下旋转角度,避免过度抬头/低头 xRotation = Mathf.Clamp(xRotation, -80f, 80f); yRotation += mouseX; // 相机负责上下+左右旋转 cam.transform.localRotation = Quaternion.Euler(xRotation, yRotation, 0); // 角色直接同步相机Y轴旋转,保证水平方向完全对齐 transform.rotation = Quaternion.Euler(0, yRotation, 0); } }
2. 修正PlayerMotor.cs(基于相机朝向移动)
using UnityEngine; public class PlayerMotor : MonoBehaviour { // 确保玩家对象挂载CharacterController组件,并拖入此变量 public CharacterController controller; public float moveSpeed = 5f; public float gravity = -9.81f; private Vector3 velocity; public void ProcessMove(Vector2 input) { // 获取相机的前向/右向向量,剔除Y轴分量保证水平移动 Vector3 cameraForward = Camera.main.transform.forward; Vector3 cameraRight = Camera.main.transform.right; cameraForward.y = 0; cameraRight.y = 0; // 归一化向量,避免斜向移动时速度过快 cameraForward.Normalize(); cameraRight.Normalize(); // 计算最终移动方向:W/S对应相机前后,A/D对应相机左右 Vector3 moveDirection = cameraForward * input.y + cameraRight * input.x; // 执行移动 controller.Move(moveDirection * moveSpeed * Time.deltaTime); // 重力处理,保持角色贴地 if (controller.isGrounded && velocity.y < 0) { velocity.y = -2f; // 轻微贴地力,防止悬空 } velocity.y += gravity * Time.deltaTime; controller.Move(velocity * Time.deltaTime); } public void Jump() { // 仅在地面时允许跳跃 if (controller.isGrounded) { // 调整数值可改变跳跃高度 velocity.y = Mathf.Sqrt(3f * -gravity); } } }
场景配置检查
- 玩家对象必须挂载
CharacterController组件,并在PlayerMotor面板中赋值给controller变量。 - 相机需作为玩家对象的子对象,且
PlayerLook面板中的cam变量已拖入场景相机。 - 根据手感调整
xSensitivity和ySensitivity数值,找到合适的鼠标旋转速度。
内容的提问来源于stack exchange,提问作者roee
相关产品推荐
相关产品推荐

