首页 > 解决方案 > 如何在 Unity 中使用 Lerp Dash 运动

问题描述

我正在 Unity 中做一个初学者项目,并想使用 Vector3.Lerp 为破折号运动做动画。这是我的代码,我正在努力找出它为什么不起作用。

    void Update()
    {
        if (Input.GetKeyDown(KeyCode.E))
        {
            Vector3 start = transform.position;
            Vector3 dash = new Vector3(start.x + m_DashDist, start.y);
            transform.position = Vector3.Lerp(start, dash, Time.deltaTime);
        }
    }

标签: unity3d

解决方案


Lerp工作原理

您传递给Lerp函数的最后一个参数是一个浮点值(主要在0f和之间1f)。

  • 如果此值为0fLerp将返回第一个参数(假设为_dashStart)。
  • 如果此值为1fLerp将返回第二个参数(假设为_dashEnd)。
  • 如果此值为0.5fLerp将返回第一个和第二个参数之间的“中间值”。

如您所见,此函数根据第三个参数在这两个参数之间进行插值。

Time.deltaTime必须每帧调用此函数,并且在您的情况下,浮点值(第三个参数)需要每帧递增。

但是你的 if 块只执行一次,当你按下时E。例如,您可以在按键被按下bool时将 a 设置为 true 。E这是进一步的代码——希望没有错误:

public float dashTime = 0.1f;

private float _currentDashTime = 0f;
private bool _isDashing = false;
private Vector3 _dashStart, _dashEnd;

void Update()
{
    if (Input.GetKeyDown(KeyCode.E))
    {
        if (_isDashing == false)
        {
            // dash starts
            _isDashing = true;
            _currentDashTime = 0;
            _dashStart = transform.position;
            _dashEnd = new Vector3(_dashStart.x + m_DashDist, _dashStart.y);
        }
    }

    if (_isDashing)
    {
        // incrementing time
        _currentDashTime += Time.deltaTime;

        // a value between 0 and 1
        float perc = Mathf.Clamp01(_currentDashTime / dashTime);

        // updating position
        transform.position = Vector3.Lerp(_dashStart, _dashEnd, perc);

        if (_currentDashTime >= dashTime)
        {
            // dash finished
            _isDashing = false;
            transform.position = _dashEnd;
        }
    }
}

有不同的使用方法Lerp。我主要使用这种方法。


推荐阅读