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

Unity角色Dash功能无位移但Debug日志正常问题排查

问题分析与修复方案

核心问题点

  1. 冲刺方向丢失:冲刺依赖实时direction变量,若按下冲刺键时未按住移动键,direction会被重置为Vector2.zero,再经FixedUpdate里的Normalize()处理后仍为零,导致冲刺无方向。
  2. 移动逻辑冲突:同时使用rb.velocity和rb.MovePosition控制刚体,两者会互相干扰,Unity中刚体移动应仅选用一种方式。
  3. 仅支持X轴冲刺:当前代码只处理X轴位移,完全忽略Y轴,角色无法上下冲刺。
  4. 执行顺序冗余:MoveCharacter中isDashing时设置rb.velocity = Vector2.zero,虽然后续CheckDash会覆盖,但逻辑冗余且易混淆。

修复步骤

1. 保存冲刺触发时的方向

新增变量存储冲刺方向,避免依赖实时输入:

// 在Dash变量区域添加
private Vector2 dashDirection;

修改AttemptToDash方法,保存触发冲刺时的移动方向:

private void AttemptToDash()
{
    isDashing = true;
    DashTimeLeft = DashTime;
    LastDash = Time.time;
    // 保存冲刺触发时的方向,确保松开方向键仍有冲刺方向
    dashDirection = direction.normalized;
    // 处理无方向输入的情况,默认向右冲刺
    if (dashDirection == Vector2.zero)
    {
        dashDirection = Vector2.right;
    }

    PlayerAfterImagePool.Instance.GetFromPool();
    LastImageExp = transform.position.x;
}

2. 统一移动方式,支持全方向冲刺

修改CheckDash方法,仅用rb.velocity控制冲刺(符合物理引擎逻辑),并支持XY轴全方向:

private void CheckDash()
{
    Debug.Log("Checking Dash");

    if (isDashing)
    {
        Debug.Log("Dashing");

        if (DashTimeLeft > 0)
        {
            // 使用保存的冲刺方向,支持全轴位移
            rb.velocity = dashDirection * DashSpeed;
            DashTimeLeft -= Time.deltaTime;

            // 移除rb.MovePosition,避免和velocity冲突
            if (Vector2.Distance(transform.position, new Vector2(LastImageExp, transform.position.y)) > DistanceBetweenImages)
            {
                PlayerAfterImagePool.Instance.GetFromPool();
                LastImageExp = transform.position.x;
            }
        }

        if (DashTimeLeft <= 0)
        {
            isDashing = false;
            Debug.Log("Dash finished");
            // 重置速度,避免冲刺后残留惯性
            rb.velocity = Vector2.zero;
        }
    }
}

3. 优化MoveCharacter逻辑

移除isDashing时设置rb.velocity = Vector2.zero的代码,避免覆盖冲刺速度:

private void MoveCharacter()
{
    // 仅非冲刺状态处理常规移动
    if (!isDashing)
    {
        rb.velocity = direction * speed;
    }
}

4. 检查Inspector参数配置

确保Unity编辑器中给PlayerController组件设置合理数值:

  • DashSpeed:设为远大于常规移动速度的值(如20-30,根据游戏缩放调整)
  • DashTime:设为合理持续时间(如0.2-0.5秒)
  • DashCooldown:设为冷却时间(如1-2秒)

额外建议

  • 给冲刺添加专属动画状态,在isDashing为true时触发,提升反馈感
  • 冲刺时可暂时关闭碰撞或添加无敌帧,增强游戏体验

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 06:05:54