You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Unity角色转向时同步旋转物体并沿面朝方向移动的实现问题

Unity角色同步转向+面朝方向移动实现方案

现有代码问题排查

  • 存在多处语法错误:Input.GetAxisRaw("Vertical") 缺少闭合引号,FixedUpdate 首字母错误写成大写Void(C#中方法返回值关键字为小写void),移动计算时transform.TransformDirection(moveDirection)和moveSpeed之间缺少乘号
  • 缺失转向控制逻辑:仅实现了沿面朝方向移动的基础逻辑,没有添加根据输入同步旋转角色的代码

修复后的完整实现代码

using UnityEngine;

public class PlayerMovement : MonoBehaviour
{
    [Header("移动参数")]
    public float moveSpeed = 5f;
    public float rotateSpeed = 10f;
    private Vector3 moveDirection;
    private Rigidbody rb;

    void Awake()
    {
        // 提前缓存Rigidbody组件,避免每帧调用GetComponent产生性能消耗
        rb = GetComponent<Rigidbody>();
    }

    void Update()
    {
        // 获取输入
        float horizontalInput = Input.GetAxisRaw("Horizontal");
        float verticalInput = Input.GetAxisRaw("Vertical");
        moveDirection = new Vector3(horizontalInput, 0, verticalInput).normalized;
    }

    void FixedUpdate()
    {
        Move();
        Rotate();
    }

    // 沿角色当前面朝方向移动
    void Move()
    {
        Vector3 worldMoveDir = transform.TransformDirection(moveDirection);
        rb.MovePosition(rb.position + worldMoveDir * moveSpeed * Time.fixedDeltaTime);
    }

    // 转向逻辑
    void Rotate()
    {
        // 有输入时才触发转向
        if (moveDirection.magnitude > 0.1f)
        {
            Quaternion targetRotation = Quaternion.LookRotation(moveDirection, Vector3.up);
            // 平滑旋转,rotateSpeed越大转向越快
            transform.rotation = Quaternion.Lerp(transform.rotation, targetRotation, rotateSpeed * Time.fixedDeltaTime);
        }
    }
}

逻辑说明

  • 移动逻辑:通过transform.TransformDirection将本地坐标系下的移动输入转换为世界坐标系下的移动向量,保证角色始终沿着自身当前面朝方向移动
  • 转向逻辑:当检测到有移动输入时,通过Quaternion.LookRotation计算出目标朝向,再用Quaternion.Lerp做平滑过渡,保证角色转向动作和输入同步执行
  • 优化点:提前在Awake中缓存Rigidbody组件,避免每帧调用GetComponent产生额外性能开销,移动和转向逻辑都放在FixedUpdate中执行,符合物理帧更新的规范

内容的提问来源于stack exchange,提问作者Enishan Topuz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 07:06:06