Nerd For Tech
Published in

Nerd For Tech

Custom 3D Character Controller

Objective: Create a character that move and jump in a 3D environment.

We’ll begin by adding a Character Controller component to capsule object. We’ll change the Step Offset to “0” — this will eliminate a common problem with Unity objects “sticking” to walls and being “jittery” when encountering hard edges.

Now we’ll create our movement script. Below are the variables we’ll need.

We’ll gather all the player’s input in the Update method. We’ll only allow the jump button to be recorded if the character is grounded.

We’ll handle the actual movement in the FixedUpdate method. This will make our movement framerate independent.

If the character was falling (the velocity’s y-axis was less than zero), we’ll set it to zero.

Next we’ll handle the horizonal and vertical movement. We’ll assign the player’s input into a direction, then move the Character Controller in that direction multiplied by _speed and Time.fixedDeltaTime (the time since the last FixedUpdate).

If we accepted the jump button being pressed, we’ll handle that now. I’m using -9.81 to represent gravity. By taking the square root of our desired jump height times negative two times gravity, our character will be able to reach the jump height at the apex of their jump. With a jump height of four, we’ll be able to jump four “meters” (Unity world units), which is twice our character’s height of two meters. (Image someone 6'6" tall clearing a 13' tall hurdle!)

Finally, we’ll apply gravity and actually move the Character Controller.

The result is a very smooth and responsive character!

--

--

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