Apply Force over time

I want my character to dodge, so I was thinking of applying a force over time.
When the “dodge” button is pressed I start a coroutine that it should ensure that nothing will be executed when I enter the coroutine.
In the coroutine I do this:

private IEnumerator Dodge(Vector3 moveInput)
{
    float dodgeTime = 2.0f;
    
    // Differentiate between moving dodge and standing dodge
    if (moveInput.sqrMagnitude > 0)
    {
        while (dodgeTime > 0)
        {
            GetComponent<Rigidbody>().AddForce(transform.forward, ForceMode.VelocityChange);
            dodgeTime -= Time.fixedDeltaTime;
        }
    }
    else
    {
        while (dodgeTime > 0)
        {
            GetComponent<Rigidbody>().AddForce(-transform.forward, ForceMode.VelocityChange);
            dodgeTime -= Time.fixedDeltaTime;
        }
    }

    yield return null;
}

The problem is that the force is applied outright. I’d like more to have a transition, to see the character actually moving on the ground and not just teleporting from one position to another. Because then I want to start an animation for the actual dodge. I tried to change the ForceMode, but nothing changed.
What am I doing wrong here?

Thanks guys!

@astinog This is what you’re doing wrong: You have a loop without “rest”. No frames will be processed for the duration of this loop.

Remember that code is read in a linear fashion. What you say here is: Read no other code for 2 seconds. That also means that no frames will be processed, no physics will be processed, NOTHING except this code. So to me it sounds like it behaves just like you intended :wink:

The whole point with a Coroutine in Unity is that you can return control after one iteration of the loop and continue the loop next frame. To do this yield return null; should be INSIDE the loop. What yield return null does is that it says “Ok, we’re finished here. Lets take a break and continue next frame” and give back control to Unity for physics simulation, rendering, etc.

Atleast thats my immediate thoughts.