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

如何固定Unity角色的冲刺距离?提升速度仅加快冲刺速率

Unity 固定距离的冲刺机制实现方案

核心思路是固定冲刺距离,将冲刺持续时间动态计算为「固定距离 ÷ 冲刺速度」,这样调整速度只会改变冲刺的快慢,不会影响最终移动的距离。

修改步骤

  • 新增固定冲刺距离的参数,替换原有的固定持续时间
  • 在冲刺协程中动态计算实际需要的持续时间
  • 修正速度设置的小问题(原代码中Y轴赋值逻辑错误,应设为0)

修改后的完整代码

public Rigidbody2D rb;
private BoxCollider2D coll;
private bool movementAllowed = true; // 假设该变量已在其他地方定义

// 冲刺相关变量
[SerializeField] private float dashSpeed = 15.0f;
[SerializeField] private float dashDistance = 5.0f; // 固定冲刺距离

public void Dash()
{
    if (!movementAllowed) return; // 防止重复触发冲刺
    StartCoroutine(DashRoutine());
}

IEnumerator DashRoutine()
{
    movementAllowed = false;
    coll.isTrigger = true;

    // 冻结Y轴位置
    rb.constraints = RigidbodyConstraints2D.FreezePositionY;

    // 获取冲刺方向(基于角色当前X轴速度方向)
    float direction = rb.velocity.x < 0 ? -1 : 1;
    // 设置冲刺速度,Y轴保持0(因已冻结)
    rb.velocity = new Vector2(direction * dashSpeed, 0);

    // 动态计算冲刺持续时间:距离 ÷ 速度
    float actualDashDuration = dashDistance / dashSpeed;
    // 避免速度为0导致的异常
    if (actualDashDuration <= 0) actualDashDuration = 0.1f;

    Debug.Log("Im dashing!");

    yield return new WaitForSeconds(actualDashDuration);

    // 恢复角色状态
    rb.constraints = RigidbodyConstraints2D.None;
    coll.isTrigger = false;
    movementAllowed = true;
    // 重置速度,避免冲刺后残留速度
    rb.velocity = Vector2.zero;
}

额外说明

  • 若想基于角色朝向(而非当前速度)判断冲刺方向,可将direction的计算逻辑替换为transform.localScale.x < 0 ? -1 : 1
  • 可添加速度最小值限制,防止actualDashDuration过大导致冲刺过慢
  • 冲刺结束后重置速度,能避免角色继续保持冲刺状态移动

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 14:47:03