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

Unity中角色单方向Velocity无法停止及X轴自动减速问题求助

问题修复与解释

核心问题原因

  1. 上下键松开后角色持续移动:代码仅在按下上下键时设置Z轴速度,但松开按键后没有任何逻辑将Z轴速度重置为0。而左右键按下时会直接覆盖Velocity为X轴方向的速度(Z轴设为0),所以松开左右键后,X轴速度会被Rigidbody的阻力/地面摩擦减速到0;但Z轴速度在松开上下键后会一直保持,直到其他按键覆盖Velocity。

  2. X轴方向自动减速:这是因为Rigidbody组件的Drag(阻力)属性或地板的物理材质(Physics Material)设置了摩擦力。当松开左右键后,没有代码维持X轴速度,阻力/摩擦力会逐渐将X轴速度衰减至0。

修复代码(实现按键移动、松键停止)

修改移动逻辑,先计算输入方向,再统一设置Velocity,这样松开按键时对应轴的速度会自动归零,同时保留Y轴的原有速度(比如跳跃的速度):

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerMovement : MonoBehaviour
{
    Rigidbody rb;
    // 提前获取引用,避免每帧查找组件
    Transform playerTransform;
    Transform mainCameraTransform;
    // 可调整的速度参数
    public float moveSpeed = 5f;
    public float jumpForce = 5f;

    void Start()
    {
        rb = GetComponent<Rigidbody>();
        playerTransform = transform;
        mainCameraTransform = GameObject.Find("Main Camera").transform;
    }

    void Update()
    {
        // 优化后的相机跟随
        mainCameraTransform.position = new Vector3(
            playerTransform.position.x,
            playerTransform.position.y + 3.5f,
            playerTransform.position.z - 6f
        );

        // 计算输入方向
        float xInput = 0f;
        float zInput = 0f;

        if (Input.GetKey("up")) zInput = 1f;
        if (Input.GetKey("down")) zInput = -1f;
        if (Input.GetKey("left")) xInput = -1f;
        if (Input.GetKey("right")) xInput = 1f;

        // 设置移动速度,保留Y轴原有速度(不覆盖跳跃状态)
        rb.velocity = new Vector3(xInput * moveSpeed, rb.velocity.y, zInput * moveSpeed);

        // 跳跃逻辑
        if (Input.GetKeyDown("space"))
        {
            rb.velocity = new Vector3(rb.velocity.x, jumpForce, rb.velocity.z);
        }
    }
}

额外优化建议

  • 移除每帧GameObject.Find调用:该方法性能开销高,在Start中一次性获取引用即可。
  • 添加地面检测:当前跳跃逻辑允许空中多次跳跃,可通过Physics.Raycast或OnCollisionStay判断是否在地面,优化跳跃体验。
  • 改用Input.GetAxis:Input.GetAxis("Horizontal")和Input.GetAxis("Vertical")支持游戏手柄,且自带平滑输入,代码更简洁通用。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 22:37:43