Unity3D第三人称相机下如何沿相机朝向移动角色
解决第三人称角色沿相机视角方向移动的问题
问题分析
你的现有移动脚本直接采用世界空间的Horizontal和Vertical输入计算移动向量,导致角色始终沿世界坐标的X/Z轴移动,而非相机的视角方向。要实现相机视角相对的移动,需要基于相机的朝向转换输入向量。
修改后的移动脚本
using UnityEngine; public class MovePlayer : MonoBehaviour { private Rigidbody _playerRb; public float moveSpeed = 5f; [SerializeField] private Transform _cameraTransform; // 在Inspector面板拖拽相机到此处 private void Awake() { _playerRb = GetComponent<Rigidbody>(); } private void Update() { // 获取玩家输入 float horizontalInput = Input.GetAxis("Horizontal"); float verticalInput = Input.GetAxis("Vertical"); // 提取相机的水平前向与右向向量(忽略Y轴,保证平面移动) Vector3 cameraForward = Vector3.Scale(_cameraTransform.forward, new Vector3(1, 0, 1)).normalized; Vector3 cameraRight = Vector3.Scale(_cameraTransform.right, new Vector3(1, 0, 1)).normalized; // 基于相机方向计算最终移动向量 Vector3 moveDirection = (cameraForward * verticalInput + cameraRight * horizontalInput).normalized; // 应用移动逻辑 if (moveDirection.magnitude >= 0.1f) { _playerRb.MovePosition(transform.position + moveDirection * moveSpeed * Time.deltaTime); } } }
关键改动说明
- 添加
_cameraTransform引用,需将第三人称相机拖拽到该字段,确保脚本能获取相机朝向 - 用
Vector3.Scale剔除相机方向的Y轴分量,避免因相机上下倾斜导致角色产生垂直移动 - 基于相机的前向、右向向量,将玩家输入转换为相机视角相对的移动方向
- 对移动向量做归一化处理,防止斜向移动时速度过快
相机脚本的小修正
你的相机脚本存在变量名拼写错误,_verticalLover应改为_verticalLower,避免逻辑异常:
[SerializeField] private float _verticalLower; // 修正拼写错误
可选扩展:让角色朝向移动方向
如果需要角色移动时朝向移动方向,可在移动逻辑中添加旋转代码:
if (moveDirection.magnitude >= 0.1f) { _playerRb.MovePosition(transform.position + moveDirection * moveSpeed * Time.deltaTime); // 添加旋转逻辑 Quaternion targetRotation = Quaternion.LookRotation(moveDirection); _playerRb.MoveRotation(Quaternion.Lerp(_playerRb.rotation, targetRotation, Time.deltaTime * 10f)); }
内容的提问来源于stack exchange,提问作者Gamer's creed
相关产品推荐
相关产品推荐

