Can't figure out how to give player realistic aerial movement

Hello. I’m trying to give my character a constant velocity when I jump, but it’s really not working.

Here’s the coroutine for when the player leaves the ground:

 private IEnumerator WaitForDrop()
 {
     yield return new WaitUntil(() => !isGrounded);
     airVelocity.x = direction.x;
     airVelocity.y = direction.z;
     yield return new WaitUntil(() => isGrounded);
     StartCoroutine("WaitForDrop");
 }

The direction Vector3 is the player’s current velocity.
And this is in the main function that deals with movement:

if (!isGrounded)
            direction = new Vector3(airVelocity.x, velocity, airVelocity.y);

So, when the player goes airborne, his current x and z velocity are saved into the airVelocity Vector2.
In the main movement function, is the player is airborne, it uses the values saved in airVelocity to set the players speed. But it’s not working like it should.

WARNING: coroutines are almost never the correct solution for player controllers.

Instead use counters or timers to handle alternate control modes that may transiently occur, such as flying or sliding or jumping, etc.

If you want an example of such a controller, check this:

That one has run, walk, jump, slide, crouch… it’s crazy-nutty!!

But if you persist in your current setup…

Sounds like you wrote a bug… and that means… time to start debugging!

By debugging you can find out exactly what your program is doing so you can fix it.

Use the above techniques to get the information you need in order to reason about what the problem is.

You can also use Debug.Log(...); statements to find out if any of your code is even running. Don’t assume it is.

Once you understand what the problem is, you may begin to reason about a solution to the problem.

1 Like