Unity Beginner to Hero Part 12: Falling and Detecting Ground

In the previous lesson, we gave our controller the ability to jump. However, walking off the edge of platforms currently causes him to “snap” down off the cliff at a very high speed. In this lesson we will be adding logic to detect when the controller is touching the ground, and use this information to ensure our controller smoothly falls off surfaces.

The pull of gravity is especially strong today.

Let’s first analyze why the above behavior is occurring. When we fall off a ledge, our current downwards velocity (recall that it is stored in the yVelocity variable) is very fast. Why is this so? If we take a look at this line of code

yVelocity -= gravity * Time.deltaTime;

We’ll see that yVelocity is decreased every frame, constantly. This means even when we are standing flat on a surface, gravity is still increasing our downwards velocity! Currently, yVelocity is only reset when we jump. This is correct, but we’ll also want to zero out yVelocity whenever we are standing on the ground. Add the following code:

if (GetComponent<CharacterController>().isGrounded)
{
	yVelocity = 0;
}

Once again we retrieve the CharacterController component, and this time we check to see if the isGrounded property is set to true. If it is, we set yVelocity to zero. The precise details of how isGrounded works and robust ways to detect ground beneath characters will be talked about in future lessons. Go ahead and run the project, and you’ll see that our falling issue has been fixed. We’re nearly done with jumping and falling, but one problem still remains: the player is currently able to jump in mid-air!

I do what I want.

I do what I want.

To fix this, move the jumping code (the entire if block) into our new if block that checks if the controller is grounded. This way, we’ll only be able to jump if we’re touching the ground. Happy leaping!

Lesson 12 Complete Project


Thanks for reading! If you have any problems with the above tutorial, general comments or suggestions, please post below. It’s always appreciated!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s