Home > Back-end >  Unity Beginner Help - Lerp Dash Movement
Unity Beginner Help - Lerp Dash Movement

Time:09-28

Im new beginner in Unity. Im doing a beginner project right now and wanna use Vector3.Lerp to do animation for the dash movement. Here is my code and Im struggling to see why it didnt work. Please help me.

    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);
        }
    }

CodePudding user response:

How Lerp Works

The last argument you pass to the Lerp function is a float value (mostly between 0f and 1f).

  • If this value is 0f, Lerp will return the first argument (let's say _dashStart).
  • If this value is 1f, Lerp will return the second argument (let's say _dashEnd).
  • If this value is 0.5f, Lerp will return the "mid" between the first and the second argument.

As you can see, this function interpolates between these two arguments depending on the third argument.

This function has to be called every frame and the float value (the 3rd argument) needs to be incremented by Time.deltaTime every frame in your case.

But your if block is only executed once, when you press E. For instance, you can set a bool to true when the E key has been pressed. Here is the further code – hopefully with no mistakes:

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;
        }
    }
}

There are different ways of using Lerp. I mostly use this approach.

  • Related