Unity基于相机朝向的角色移动功能失效问题
问题:第一人称角色控制器移动方向不跟随相机视角
学习Brackeys第一人称角色控制器教程时,编写的代码无法实现根据相机角度调整角色前进方向的效果,当前实现代码如下:
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Movement : MonoBehaviour { public CharacterController controller; public float speed = 12f; public float gravity = -9.81f; public float jumpHeight = 3f; public Transform groundCheck; public float groundDistance = 0.4f; public LayerMask groundmask; Vector3 velocity; bool isGrounded; // Update is called once per frame void Update() { isGrounded = Physics.CheckSphere(groundCheck.position, groundDistance, groundmask); if(isGrounded && velocity.y < 0) { velocity.y = -2f; } float x = Input.GetAxis("Horizontal"); float z = Input.GetAxis("Vertical"); Vector3 move = transform.right * x + transform.forward * z; controller.Move(move * speed * Time.deltaTime); if(Input.GetButtonDown("Jump") && isGrounded) { velocity.y = Mathf.Sqrt(jumpHeight * -2f * gravity); } velocity.y += gravity * Time.deltaTime; controller.Move(velocity * Time.deltaTime); } }
问题原因
当前代码计算移动方向时,调用的transform.right和transform.forward是挂载Movement脚本对象的自身朝向。如果脚本挂载在玩家根对象上,而相机仅挂载在玩家子层级做上下俯仰旋转、玩家根对象没有同步跟随相机做水平Y轴旋转,移动方向就会永远固定对齐玩家初始朝向,不会随视角变化。
修复方案
- 第一步:在Movement类中新增公有字段,用于引用相机变换组件
public Transform playerCamera;
- 第二步:替换原有移动方向计算逻辑,使用相机的水平投影方向计算移动向量,避免相机俯仰带来的垂直方向偏移。将原代码中
Vector3 move = transform.right * x + transform.forward * z;替换为以下代码:
// 提取相机水平向右方向,消除垂直分量 Vector3 camRight = playerCamera.right; camRight.y = 0f; camRight.Normalize(); // 提取相机水平向前方向,消除垂直分量 Vector3 camForward = playerCamera.forward; camForward.y = 0f; camForward.Normalize(); Vector3 move = camRight * x + camForward * z;
- 第三步:回到Unity编辑器,将场景中的主相机拖到Movement脚本组件的
playerCamera参数槽位完成赋值,不要留空。
补充说明:如果是按照Brackeys教程的标准结构实现(玩家根对象仅同步水平Y轴旋转,相机作为玩家子物体仅做X轴上下俯仰),出现该问题也可能是相机未正确设置为玩家对象的子物体,或是视角控制脚本未将水平旋转应用到玩家根对象,优先检查这两处配置即可。
内容的提问来源于stack exchange,提问作者GuyInABox
相关产品推荐
相关产品推荐

