2D dash in coroutine Inconsistent

Hello, I am trying to do a 2D dash effect. I am using a coroutine to do it. The problem is that the distance the player travels is inconsistent. Its close but not fully accurate. How can I fix it? The necessary sample of the code is below. Thank you.

public override IEnumerator Cast()
    {
        canCast = false;
        controls.canMove = false;
        float curTimeLeft=dashDuration;
        controls.rb.velocity=new Vector2(0,0);
        Vector2 dasher = transform.right ;

        controls.rb.velocity = dasher*dashSpeed;
        yield return new WaitForSeconds(dashDuration);
        controls.rb.velocity=new Vector2(0,0);
        controls.canMove = true;
        yield return new WaitForSeconds(cooldown);
        canCast = true;
    }

Physics usually run on the FixedUpdate cycle which is more or less independent from the framerate and the Update cycle. WaitForSeconds can only wait approximately for the given time. Since it can only continue after a full frame the time could always be slightly more than what you have specified. Instead of

yield return new WaitForSeconds(dashDuration);

you might be able to use

float timeOut = Time.fixedTime + dashDuration;
while(Time.fixedTime < timeOut)
    yield return null;

instead.

Of course since you set your velocity only once at the beginning of your dash, it’s possible that due to collisions or friction you loose momentum. Maybe you want to set the velocity every frame during the dash?

float timeOut = Time.fixedTime + dashDuration;
while(Time.fixedTime < timeOut)
{
    controls.rb.velocity = dasher*dashSpeed;
    yield return null;
}

Hello, I really can’t figure out what causes this problem. Does anyone have any idea?