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

Unity中如何通过transform.Translate设置位移量实现一键完整冲刺?

解决Unity单次点击触发完整冲刺的问题

你的核心问题是冲刺协程只执行了一帧位移——原代码里transform.Translate只在协程启动时跑了一次,之后就进入等待状态,所以玩家只动了一下就停止了。要实现点击一次完成完整冲刺,有两种常见方案:

方案1:持续移动式冲刺(模拟加速冲刺过程)

这种方式会在dashTime时间段内让玩家持续移动,更符合真实冲刺的动画感:

修改后的代码

private Vector2 direction;
public float dashSpeed;
public float dashTime;
public float dashCountdown;
private bool isDashing;
private bool canDash = true;

void Update()
{
    direction = new Vector2(Input.GetAxisRaw("Horizontal"), Input.GetAxisRaw("Vertical"));

    // 注意用逻辑与&&,不是按位与&
    if (Input.GetButtonDown("Dash") && canDash)
    {
        // 把冲刺瞬间的方向传给协程,避免中途被输入改变
        StartCoroutine(Dash(direction));
        print("dashing");
    }
}

private IEnumerator Dash(Vector2 dashDirection)
{
    isDashing = true;
    canDash = false;
    float elapsedTime = 0f;

    // 在冲刺时间内,每帧执行位移
    while (elapsedTime < dashTime)
    {
        transform.Translate(dashDirection * dashSpeed * Time.deltaTime);
        elapsedTime += Time.deltaTime;
        yield return null; // 等待下一帧
    }

    isDashing = false;
    yield return new WaitForSeconds(dashCountdown);
    canDash = true;
}

关键修改点

  • 把冲刺瞬间的方向作为参数传入协程,防止玩家在冲刺过程中改变方向导致轨迹偏移
  • 用while循环在dashTime周期内持续执行位移,确保整个冲刺过程完成
  • 修正条件判断的&为&&,逻辑与更符合需求且效率更高

方案2:瞬间位移式冲刺(直接跳到目标位置)

如果想要点击后瞬间完成固定距离的冲刺,不需要持续移动的过程,可以直接计算总位移量一次性移动:

修改后的代码

private Vector2 direction;
public float dashSpeed;
public float dashTime;
public float dashCountdown;
private bool isDashing;
private bool canDash = true;

void Update()
{
    direction = new Vector2(Input.GetAxisRaw("Horizontal"), Input.GetAxisRaw("Vertical"));

    if (Input.GetButtonDown("Dash") && canDash)
    {
        StartCoroutine(Dash(direction));
        print("dashing");
    }
}

private IEnumerator Dash(Vector2 dashDirection)
{
    isDashing = true;
    canDash = false;

    // 计算总冲刺距离,归一化方向避免斜向冲刺速度异常
    float totalDashDistance = dashSpeed * dashTime;
    transform.Translate(dashDirection.normalized * totalDashDistance);

    isDashing = false;
    yield return new WaitForSeconds(dashCountdown);
    canDash = true;
}

关键说明

  • 用dashDirection.normalized确保方向向量长度为1,避免同时按下水平和垂直方向时,向量长度为√2导致冲刺距离翻倍
  • 一次性完成位移,适合强调瞬间爆发力的游戏场景

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 06:10:30