Making the player jump (with ground check)
2D Game Design with Unity
🕑 This lesson will take about 17 minutes
In this lesson, you will learn how to code a script written in the C# programming language that can make the player jump in a 2D game, but only when they are touching the ground or a solid object like a platform. In the previous lesson, we implemented basic jumping. In this lesson, we will improve the code by only allowing the player to jump when they are touching the ground (or a solid object like a platform or ramp).
How does it work?
We will add the following four variables to the existing code in the PlayerController script:
public Transform groundCheck; - this variable will keep track of the position of the player’s ‘feet’ by using an empty GameObject attached to the player (as a child object of the Player GameObject). The object is positioned at the player’s ‘feet’ and is used as an invisible marker
public float groundCheckRadius; - this is a float value that represents a radius to draw an invisible circle around the player’s ‘feet’ where the groundCheck object is positioned.
public LayerMask groundLayer; - this variable is used to identify the layer that will be used to identify sprites in the scene that act as ground (eg. platforms, ramps). Anything considered ground will be added to the Ground layer in Unity.
private bool isTouchingGround; - this variable is true when the player is touching the ground and false when the player is not touching the ground. The player will only be allowed to jump when this variable is set to true.
The Physics2D.OverlapCircle() function is used to get the groundCheck object attached to the player (positioned at the player’s feet), draw an invisible circle around the player’s feet using the groundCheckRadius value, and then checks if any object that is on the Ground layer (eg. a platform) is overlapping this circle - if so, the isTouchingGround variable is set to true, otherwise false. Watch the video below for the step-by-step demonstration and scroll down to view the sample code.
Game art, tiles and sprites from the Free Pixel Space Platform pack are used in this lesson video and can be downloaded from the Unity Asset Store.
Is YouTube blocked at school? Watch on Google Drive.