Unity中如何实现玩家沿输入轴移动并同步转向?
实现玩家朝向输入轴方向旋转的Unity方案
要实现玩家朝向输入轴方向旋转,你可以在现有移动逻辑基础上添加旋转控制,同时优化原代码里的跳跃逻辑(用布尔变量替代字符串判断更可靠)。以下是修改后的完整代码:
using UnityEngine; public class PlayerMovement : MonoBehaviour { public float moveSpeed = 5f; public float rotateSpeed = 10f; // 控制旋转平滑度的参数 private Rigidbody rb; public Camera playerCamera; // 改为Camera类型更直接 public float jumpForce = 5f; private bool isJumpPressed; private void Start() { rb = GetComponent<Rigidbody>(); // 确保相机不为空 if (playerCamera == null) { playerCamera = Camera.main; } } void Update() { // 检测跳跃输入,放在Update里保证输入响应及时 if (Input.GetKeyDown(KeyCode.Space)) { isJumpPressed = true; } } private void FixedUpdate() { float h = Input.GetAxis("Horizontal"); float v = Input.GetAxis("Vertical"); // 构建输入向量,忽略Y轴 Vector3 inputDir = new Vector3(h, 0, v).normalized; if (inputDir.magnitude > 0.1f) { // 将输入方向转换为世界空间(基于相机视角) Vector3 cameraForward = playerCamera.transform.forward; Vector3 cameraRight = playerCamera.transform.right; // 忽略相机的Y轴倾斜,保持水平方向 cameraForward.y = 0; cameraRight.y = 0; cameraForward.Normalize(); cameraRight.Normalize(); // 计算最终的移动方向 Vector3 moveDir = cameraForward * v + cameraRight * h; moveDir.Normalize(); // 设置移动速度 rb.velocity = new Vector3(moveDir.x * moveSpeed, rb.velocity.y, moveDir.z * moveSpeed); // 计算目标旋转方向,让玩家朝向移动方向 Quaternion targetRotation = Quaternion.LookRotation(moveDir); // 平滑旋转到目标方向,用MoveRotation保证物理同步 rb.MoveRotation(Quaternion.Lerp(rb.rotation, targetRotation, rotateSpeed * Time.fixedDeltaTime)); } else { // 没有输入时保持Y轴速度,XZ轴速度归0 rb.velocity = new Vector3(0, rb.velocity.y, 0); } // 处理跳跃 if (isJumpPressed) { // 给刚体添加向上的力,或者直接设置Y轴速度(根据需求选择) rb.velocity = new Vector3(rb.velocity.x, jumpForce, rb.velocity.z); isJumpPressed = false; } } }
关键修改说明:
- 旋转逻辑:当有移动输入时,先将输入方向转换为基于相机视角的世界空间方向,再通过
Quaternion.LookRotation生成目标旋转,最后用Quaternion.Lerp配合Rigidbody.MoveRotation实现平滑旋转,保证旋转和物理系统同步。 - 输入方向优化:基于相机视角转换输入方向,玩家的WSAD操作会始终对应相机的前后左右,符合常规游戏操作逻辑。
- 跳跃逻辑优化:用布尔变量
isJumpPressed替代原有的字符串判断,避免字符串比较的潜在问题,同时用Input.GetKeyDown确保跳跃只触发一次。 - 代码规范:重命名脚本和变量为更清晰的名称(比如
moving改为PlayerMovement,r改为rb),提升代码可读性。
内容的提问来源于stack exchange,提问作者HiWhy
相关产品推荐
相关产品推荐

