Player Jump in 2D Setting

Niraj Karki
3 min readSep 3, 2021

--

2D Mobile Game

Objective: Allow player to jump only when grounded and when player hits Space key.

To start off, create a layer and add your ground with collider to that layer. We do this so that we can allow the raycast to hit only the collider with this layer and ignore all other colliders.

Then inside the player script, create a jump force variable which will determine how high the player can jump with respect to the gravity.

Then create a function with return type bool which we will be using to determine if the player is on the ground before allowing to jump.

Here, we are using raycast to draw a ray which starts from player position downwards to 0.6f length and only hit the layer 6 which is the ground we added earlier.

If the raycast hits the ground layer collider then the function returns true and if not it will return false.

If you feel that using the 1<<6 is harder to understand then you can also create a layermask variable and use the value of that layermask to the raycast.

Just make sure that you select the Ground layer in the variable to make sure that raycast hits the ground.

If you have a player with different size and you don’t know if the ray is hitting the ground then you can draw a ray from the origin with given length in given direction. With this you can determine how long of a ray you want.

And finally check if the player is pressing the Space key and if the player is on the ground. If both are true then change the velocity in y-axis to make the player jump and we are using the jump force variable to provide the jump height.

And this is the final result.

--

--