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

Unity技术问题:物体移动值无法归零导致无法停止移动

Unity物体无法停止移动的问题修复

你的问题核心不是moveHorizontal没回到0——Input.GetAxisRaw("Horizontal")在松开按键时确实会重置为0,真正原因是你用了ForceMode2D.Impulse给刚体加瞬时力,松开按键后刚体因为物理惯性(没有阻力)会一直保持运动状态。

下面给两种实用的修复方案:

方案1:直接控制刚体速度(精确控制移动)

这种方式会直接覆盖刚体的水平速度,松开按键时速度立刻归0,物体马上停止,适合平台跳跃类游戏的精确移动:

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

public class Movement : MonoBehaviour
{
    private Rigidbody2D rb2D;
    private float speed = 5f; // 可根据需求调整速度值
    private float moveHorizontal;

    void Start()
    {
         rb2D = GetComponent<Rigidbody2D>();
    }
  
    void Update()
    {
         moveHorizontal = Input.GetAxisRaw("Horizontal");
    }

    void FixedUpdate()
    {
        // 只修改水平速度,保留y轴原有速度(兼容跳跃等其他逻辑)
        rb2D.velocity = new Vector2(moveHorizontal * speed, rb2D.velocity.y);
    }
}

方案2:物理驱动的移动(带自然减速)

如果想保留物理加力的真实感,可以通过添加阻力或反向力让物体自然停下:

方法A:直接调整刚体参数

选中你的游戏物体,在Inspector面板的Rigidbody2D组件中,把**Linear Drag(线性阻力)**设置为1-3之间的数值,物体会在松开按键后自然减速停止。

方法B:代码实现停止逻辑

在没有输入时施加反向力抵消当前速度,模拟刹车效果:

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

public class Movement : MonoBehaviour
{
    private Rigidbody2D rb2D;
    private float speed = 25f; // 加力需要更大的数值,可自行调整
    private float moveHorizontal;
    private float stopForce = 12f; // 停止用的反向力强度

    void Start()
    {
         rb2D = GetComponent<Rigidbody2D>();
    }
  
    void Update()
    {
         moveHorizontal = Input.GetAxisRaw("Horizontal");
    }

    void FixedUpdate()
    {
        if (moveHorizontal != 0)
        {
            rb2D.AddForce(new Vector2(moveHorizontal * speed, 0f), ForceMode2D.Impulse);
        }
        else
        {
            // 无输入时施加反向力,抵消当前水平速度
            rb2D.AddForce(new Vector2(-rb2D.velocity.x * stopForce, 0f));
        }
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 22:25:26