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

Unity Engine:添加2D移动脚本后刚体下落缓慢问题

解决Unity 2D移动脚本导致下落缓慢的问题

问题出在你的FixedUpdate方法中——你完全替换了Rigidbody2D的velocity属性,包括y轴分量。当没有垂直输入时,moveDirection.y为0,这会强制把物体的y轴速度设为0,直接覆盖了Unity物理引擎的重力效果,导致物体无法正常下落。

以下是修正后的代码,只修改水平方向的速度,保留y轴的物理效果(包括重力):

public class Movement : MonoBehaviour
{
    public Rigidbody2D rb;

    public float moveSpeed = 4f;
    public InputAction playerControl;

    Vector2 moveDirection = Vector2.zero;

    private void OnEnable()
    {
        playerControl.Enable();
    }
    private void OnDisable()
    {
        playerControl.Disable();
    }

    void Update()
    {
        moveDirection = playerControl.ReadValue<Vector2>();
    }

    private void FixedUpdate()
    {
        // 仅控制水平速度,保留y轴的物理模拟(重力、碰撞等)
        rb.velocity = new Vector2(moveDirection.x * moveSpeed, rb.velocity.y);
    }
}

如果你的输入需要支持垂直控制(比如跳跃),可以调整逻辑,只有当存在有效垂直输入时才修改y轴速度:

private void FixedUpdate()
{
    Vector2 newVelocity = rb.velocity;
    // 水平方向由输入完全控制
    newVelocity.x = moveDirection.x * moveSpeed;
    
    // 当垂直输入的绝对值大于阈值时,才覆盖y轴速度
    if (Mathf.Abs(moveDirection.y) > 0.1f)
    {
        newVelocity.y = moveDirection.y * moveSpeed;
    }
    
    rb.velocity = newVelocity;
}

这样修改后,移动功能保持正常,同时物体的下落会遵循Unity的重力设置,恢复预期的物理效果。

内容的提问来源于stack exchange,提问作者Calliope Harris-Walker

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 11:25:21