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

Unity中如何将玩家现有动量强制转向冲刺方向?

Unity冲刺功能手感优化:保留并转换当前动量

问题根源

你当前代码里的rb.linearVelocity = Vector3.zero;是导致手感滞涩的核心——它直接清零了玩家所有原有动量,冲刺时会有突兀的“断档”感,完全丢失了之前的运动惯性。

修改方案

核心思路是保留玩家当前的动量,只在冲刺方向上叠加冲刺力,同时可以选择性保留垂直于冲刺方向的原有速度,让冲刺动作更顺滑自然。

修改后的Dash方法代码

private void Dash()
{
    if(dashCdTimer > 0) return;
    dashCdTimer = dashCd;

    cam.DoFov(dashFov);
    Transform forwardT = orinetation;

    // 获取玩家输入的冲刺方向
    Vector3 dashDirection = GetDirection(forwardT).normalized;

    // 提取当前速度中,垂直于冲刺方向的分量(保留横向/纵向的原有运动惯性)
    Vector3 currentVelocity = rb.linearVelocity;
    Vector3 perpendicularVelocity = currentVelocity - Vector3.Project(currentVelocity, dashDirection);

    // 计算冲刺带来的速度变化(根据刚体质量转换为力的效果)
    float dashSpeed = dashForce / rb.mass;
    Vector3 dashVelocity = dashDirection * dashSpeed;

    // 合并速度:保留垂直方向动量,叠加冲刺方向速度
    rb.linearVelocity = perpendicularVelocity + dashVelocity;

    // 可选:如果想保留部分原有冲刺方向的动量,调整为下面这行
    // Vector3 dashVelocity = dashDirection * dashSpeed + Vector3.Project(currentVelocity, dashDirection) * 0.5f;

    // 添加向上冲刺力(如果需要保留原有垂直速度,也可以用投影方法处理)
    rb.AddForce(orinetation.up * dashUpwardForce, ForceMode.Impulse);

    Invoke(nameof(ResetDash), dashDuration);
}

可选优化:GetDirection函数

用向量长度判断替代输入值判断,避免浮点精度问题:

private Vector3 GetDirection(Transform forwardT)
{
    float horizontal = Input.GetAxisRaw("Horizontal");
    float vertical = Input.GetAxisRaw("Vertical");

    Vector3 direction = forwardT.forward * vertical + forwardT.right * horizontal;
    // 当输入向量长度大于阈值时才归一化,否则用默认前方向
    return direction.magnitude > 0.1f ? direction.normalized : forwardT.forward;
}

关键逻辑说明

  1. 保留垂直动量:通过Vector3.Project把当前速度分解为“冲刺方向分量”和“垂直冲刺方向分量”,保留垂直分量让玩家在横向移动时冲刺,不会突然丢失横向速度。
  2. 叠加冲刺力:冲刺方向的速度由冲刺力决定,你可以通过调整dashSpeed的计算或者添加原有冲刺方向分量的比例,进一步优化手感(比如保留50%原有冲刺方向动量)。
  3. 移除速度清零:删掉rb.linearVelocity = Vector3.zero;,彻底解决突兀的动量丢失问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.13 15:33:16