Building a Basic Character Controller in Unity

Jon Jenkins
3 min readJun 29, 2021

--

Here I will demonstrate how to code a basic character controller using Unity’s Character Controller component.

Start by adding a character controller component to your player object. I’ve also added a Player script that is used to control and process player input and interact with the character controller. The controller comes with its own collider.

That’s basically all you need on your player game object to continue. Now lets talk about the code involved.

I declared a private float _speed to represent how fast the player will move.

In the start method above we first grab a reference to our character controller component.

In Update we first read the Horizontal input and create a vector for the direction based on the input. We next create a velocity vector, which is the direction vector scaled by the speed. Finally we pass this vector to the controller’s move method which will move our player.

Next we add gravity, which will make our player return to the ground when they jump. Gravity is defined like so:

Now we will change the Update method to reflect the addition of gravity. Here we are only applying gravity if the player is not already grounded. Gravity is set as the y value of our velocity vector:

Now we have a basic character controller that behaves like this:

Next, we want to add the ability for the player to jump to our controller. Below, we detect a jump by checking to see if the space bar has been pressed. If we jump, we set the y component of our velocity vector to the jump height that we can set depending on how high the player can jump.

If the player is already in the air then we simply set the y component of velocity equal to itself minus our gravity value:

Below we see the final controller with the ability to move and jump. The jump height and gravity values can be modified to change the feel of the controller.

--

--

Jon Jenkins
Jon Jenkins

Written by Jon Jenkins

A Unity Developer, interested in all things Unity.

No responses yet