Platformer: Simple Movement & Jump

Intro

In this article, I will go over another way to create simple player movement and jumping mechanic using a character controller.

Setup

On the Player game object, we add a Character Controller and modify the radius, height, and center it to encapsulate the player.

The Code

First, we will get a handle on the Character Controller.

In Update, we only want to be able to move and jump if the player is touching the ground. We will check to see if the character controller is touching the ground is true. Next, we are going to create a local float variable that will store the input value of the left and right arrow key. Pressing the left arrow key will go from 0 to -1 and the right arrow key will go from 0 to 1.

Once we have that float value, we are going to create a new Vector3 that is going to be the direction the character is moving in on the x-axis. Now that we have this updating Vector3, we can move the character controller using that direction multiplied by the time between frames.

Gravity

At this point we should be able to move left and right, but it is not working because the character controller isn’t grounded. Let’s add gravity to ensure the character controller is grounded.

We are going to serialize the float variable that will allow us to adjust the gravity value in the inspector. Now, if the character is not grounded (it is in the air) we will subtract the gravity value from the direction Vector3 on the y-axis.

We are moving, but extremely slow.

Lets declared a float variable that will store the speed value and serialize it so e can adjust in the inspector. Where we are calculate the direction, we will now will want to multiply it by the speed value.

Jumping

In adding jumping, we will serialize a float variable that will store the jumping height. If the character controller is grounded we will want to be able to press the space bar to jump. Once the space bar is press we add the jump height value to the Vector3 direction on the y-axis. This will have the character move up, meaning it is no longer grounded, so gravity will take over.

--

--

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