In this article, we will make a physics-based movement using the Character Controller component in Unity. The reason to do it this way rather than using a Rigidbody component is to give us more control over the movement.
The scene is straightforward, with cubes for Platforms and a capsule for the Player. On the Player GameObject, we remove the Capsule Collider and replace it with a Character Controller and add the new Player script. The Character Controller already acts as a Collider, so there is no need for the Capsule Collider.
The Character Controller has functions for moving the GameObject, and it gives us some settings for going up slopes and climbing steps. For more on the settings and functions, you can check out the documentation.
To get the Player moving, we will need a variable for the speed and a reference to the Character Controller that we retrieve in Start. Then in Update, we use the Move function on the Controller in the direction of the Horizontal Input at speed multiplied by the time since the last frame.
Now the Player can move left and right but will not fall when leaving the platform.
To add gravity and the ability to jump to Player, we need a few more variables. We need one to drag the Player downward each frame when it is not touching the ground, the next is the amount the Player moves upward when jumping, and the last is to keep track of the velocity on the y-axis.
In Update, we use the Character Controller’s isGrounded bool to check if the Player is on the ground. Then if the space key is pressed, the y axis velocity is set to the jump height, and the velocity’s y-axis is set to the stored y-axis velocity. If the Player is not grounded, we subtract gravity from the stored y-axis velocity.
Now the Player can jump and is pulled down by gravity. You may need to adjust the gravity and jump height amounts until you get your game’s desired feel.
To get the camera to follow the Player, you can make it a child of the Player GameObject. It is not the most elegant solution but great for prototyping. In the following article, we will add a double jump for the Player to use.