Simple platformer controls in Unity
Let’s go over how to implement simple platformer controls.
First, start with adding a few cubes to the scene for the player to stand on and position them:
Add a capsule for the basic geometry for the player:
Create a script called Player and attach it to the player object. Set the tag of the player object to Player:
Select the player object and add a Character Controller:
Open up the Player script. For the controls we need a reference to the CharacterController, a float for the movement speed, a float for the gravity, a float for jump height and a float to check the current Y velocity (jumping or falling):
In the Start function initialize the Character Controller:
In the Update function get the horizontal direction from the horizontal input(Project Setting ->Input Manager). Get the velocity by multiplying direction with speed. Check if the player is on the ground. If the player is on the ground and the space key is pressed, set the Y velocity to jump height. If the player is not on the ground, subtract the Y velocity by gravity and ensure it is also multiplied by Time.deltaTime to make it frame independent:
Lastly, set the Y value on the main velocity to Y velocity and then call the Move function on the Character Controller and pass in the main velocity multiplied by Time.deltaTime:
Set the serialized values on the Inspector:
To make the camera follow the player, create another script called FollowCamera and attach it to the main camera. You could also add the camera as a child on the player object. However, if you later on add rotation to the player, the camera will rotate as well:
Open up the FollowCamera script. Add a Transform for the camera target and a Vector3 for the distance offset between the camera and the target. When updating the position of the camera, it is best to use the LateUpdate function instead of Update. This will ensure that the player moves before the camera and prevents the camera from jittering:
The whole Player script:
Good luck!