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

如何将Unity俯视角角色加减速从Lerp改为四次缓动曲线?

问题:用四次缓动曲线替换俯视角角色移动的线性加减速

我尝试寻找合适的实现方法已有一段时间,最终决定正式请教。目前我使用以下代码片段控制俯视角角色移动:

Vector2 desiredVelocity = input.movementAxis * Mathf.Max(stats.movementSpeed.Value, 0f);

float maxSpeedChange;
if (input.movementAxis != Vector2.zero)
    maxSpeedChange = acceleration;
else
    maxSpeedChange = deceleration;

velocity.x = Mathf.MoveTowards(velocity.x, desiredVelocity.x, maxSpeedChange);
velocity.y = Mathf.MoveTowards(velocity.y, desiredVelocity.y, maxSpeedChange);

该代码通过Unity的Mathf.MoveTowards函数实现角色加减速,但MoveTowards基于线性插值,我希望改用四次缓动曲线来调整加减速效果,却不知如何将其整合到现有代码中。能否修改现有代码实现这一需求?最好无需新增当前作用域以外的变量。


解决方案

可以直接在原有代码结构上修改,用四次缓动公式替换线性插值逻辑,不需要新增作用域外变量。核心思路是:

  • 加速阶段使用t^4曲线:初始速度变化平缓,后期加速越来越快
  • 减速阶段使用1-(1-t)^4曲线:初始减速迅速,接近停止时减速放缓

修改后的完整代码:

Vector2 desiredVelocity = input.movementAxis * Mathf.Max(stats.movementSpeed.Value, 0f);

// 计算当前速度与目标速度的差值
Vector2 velocityDelta = desiredVelocity - velocity;
// 区分加减速,确定单次帧的最大速度变化量
float maxSpeedChange = input.movementAxis != Vector2.zero ? acceleration : deceleration;

// 计算每个轴的缓动参数t,限制在0-1区间(t=0表示无差值,t=1表示差值等于最大允许变化量)
float tX = Mathf.Clamp01(Mathf.Abs(velocityDelta.x) / maxSpeedChange);
float tY = Mathf.Clamp01(Mathf.Abs(velocityDelta.y) / maxSpeedChange);

// 应用四次缓动曲线
if (input.movementAxis != Vector2.zero)
{
    // 加速:t的四次方
    tX = tX * tX * tX * tX;
    tY = tY * tY * tY * tY;
}
else
{
    // 减速:1减去(1-t)的四次方
    tX = 1 - Mathf.Pow(1 - tX, 4);
    tY = 1 - Mathf.Pow(1 - tY, 4);
}

// 根据缓动参数更新速度
velocity.x += Mathf.Sign(velocityDelta.x) * tX * maxSpeedChange;
velocity.y += Mathf.Sign(velocityDelta.y) * tY * maxSpeedChange;

// 兜底处理:防止浮点精度问题导致速度超过目标值
velocity.x = Mathf.MoveTowards(velocity.x, desiredVelocity.x, float.MaxValue);
velocity.y = Mathf.MoveTowards(velocity.y, desiredVelocity.y, float.MaxValue);

关键细节说明

  • 使用Mathf.Clamp01确保缓动参数t始终在0到1之间,避免因差值过大导致曲线失效
  • 用Mathf.Sign保留速度差值的方向,保证角色朝正确方向移动
  • 最后用Mathf.MoveTowards做兜底,避免浮点计算误差导致速度超出目标值

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 01:50:16