Nerd For Tech
Published in

Nerd For Tech

Character Controller in Unity

Now that I have started a new project it is time to work on the character controller for my player.

To start, add the character controller component to the player.

Now create a new player script and attach it to the player.

Movement

For the character controller, you are going to need variables for speed, jump height, and gravity. You will also need variables for the character controller and a variable to hold the player's y-axis value.

Note: I will explain the two gravity variables later

In the start method set your character controller variable.

Create a method that will handle the player movement and call this in the update method to make your code easier to read and more organized.

In the movement method, create variables to hold the horizontal and vertical input of the player. You will then create a vector 3 to store the player's position and then another vector 3 for the player's velocity.

Call the Move method for the character controller and you will get the player moving.

Gravity

Now it is time to apply gravity.

To get the gravity variable, take the gravity value multiplied by Time.deltaTime and the gravity multiplier. I found that this gives the player a good feeling jump by smoothing it out with Time.deltaTime and then multiplying by a gravity multiplier to control how fast the player will fall.

Examples:

Gravity Multiplier is 1
Gravity Multiplier is 4.5

Use an if statement to check if the player is grounded. If the player is not grounded subtract gravity from the player's y velocity.

This will apply gravity to the player.

Jump

Adding jumping is very simple.

If the player is grounded and hits the space key, set the player's y value to the jump height.

This will allow the player to jump.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store