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

为玩家添加减速效果:无加速物理,按键即满速、松键减速

实现即时最大速度+松开减速的移动逻辑

你可以通过区分有输入和无输入两种状态来实现需求:按下移动键时直接拉满速度,松开时平滑减速到0。修改后的代码如下:

private float horizontal;
public float speed = 10f;
// 控制减速快慢,值越大减速越快
public float deceleration = 6f;
[SerializeField] private Rigidbody2D rb;

private void Update()
{
    // 输入读取放在Update里,保证响应及时
    horizontal = Input.GetAxisRaw("Horizontal");
}

private void FixedUpdate()
{
    if (horizontal != 0)
    {
        // 有输入时直接设置最大速度,无加速过程
        rb.velocity = new Vector2(horizontal * speed, rb.velocity.y);
    }
    else
    {
        // 无输入时,让X轴速度逐渐趋近于0,实现减速效果
        float newXVelocity = Mathf.MoveTowards(rb.velocity.x, 0f, deceleration * Time.fixedDeltaTime);
        rb.velocity = new Vector2(newXVelocity, rb.velocity.y);
    }
}

关键逻辑说明:

  • 输入读取位置:把Input.GetAxisRaw移到Update中,确保每帧都能及时获取输入状态,避免FixedUpdate固定时间步带来的输入延迟。
  • 有输入时的处理:直接将刚体X轴速度设置为horizontal * speed,按下键瞬间就达到最大移动速度,完全跳过加速过程。
  • 无输入时的减速:使用Mathf.MoveTowards让当前X轴速度每帧向0靠近,步长为deceleration * Time.fixedDeltaTime——乘上Time.fixedDeltaTime是为了让减速速率不受帧率影响,保证不同设备上减速效果一致。你可以调整deceleration的值来控制减速的快慢。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 16:47:31