We already know the importance of prototyping. In the platformer game, we need the player to resist the gravitational force and some other obstacles that we are going to create in the game. First, start with creating a capsule that represents the player.
An option here might be to add a rigidbody component and manipulate it from the script. However, Unity has a Character Controller component and we are going to use it for this game — which will require us to define the gravity (since we do not have a rigidbody component), speed or other acting variables. Here’s the definition of Character Controller from Unity Manual:
A CharacterController allows you to easily do movement constrained by collisions without having to deal with a rigidbody.A CharacterController is not affected by forces and will only move when you call the Move function. It will then carry out the movement but be constrained by collisions.
Briefly, we need to create every force to be acted upon our character ourselves, including the gravity.
Once we add the Character Controller component to the game object, it comes with a ready collider. Thus, if you already have a collider on your game object, do not forget to remove it.
To get the character move, we need to use CharacterController.Move method, which you can access the details on here. Here’s a shot to get the player moving on the horizontal axis:
Now, you will realize that our character moves horizontally according to our inputs.
However, there is no gravity acting upon our character yet. As stated above, we need to create the gravity force by ourselves within the script: by simply declaring a gravity variable and adding it as a minus velocity on the Y axis. Likewise, we need a jump height to be added once we hit the space key.
Furthermore, we need to make sure that we can double jump once we hit the space key in mid-air. The script is provided below. Just an edit, at first double jump at 1.5x of the normal height looked like a good idea but I changed it to actual jump height later on — you can just try and error the provided variables according to your desire.
To avoid changing the y speed to 0 on every frame (because of the Vector3 velocity = direction * _speed), we have created a new variable as yVelocity. It is crucial to note that our character controller will take the move command at the end, so that it will gather all inputs correctly.
So far, we have not dealt with collecting the collectables yet. Thus, here is a quick shot of the game so far:
The movement, the gravity and the jump functions just as desired!