Are you grounded?
Objective: Using raycasting to check if the player is grounded.
In this one we are going to use raycasting, a function inside of unity, to check if our player is grounded. This can be super useful and one of many different ways to be able to check if the player is on a jumpable surface.
A raycast is a line/ray that is projected from a point, in a direction, for a distance, and if needed, restricted to a layer. They can be used in so many different ways. Say you want to know if your gun hits a target, also known as hitscan weapons, yup, raycast. How about you want to make a point and click game, raycast again, using where the ray hits as the position for the player to move to. There are many more uses for them, those are just a few, but with this game, we are using it to check if the player is grounded and able to jump.
For movement, I’m just using a simple get axis call for horizontal and using that to set the velocity of a rigidbody2d to move the player.
Now to add in the jump, check if the space key is pressed and then add a jump force.
With that, we have a moving player but….
Since we aren’t checking if the player is on the ground, the player can just keep jumping to the moon!
This is where raycasting comes into play. If we cast a ray from the player down to the ground, we can check if the ray hit anything and if it doesn’t, don’t let the player keep jumping.
Using the Physics2D in unity lets us use the raycast function we will need. Since a raycast returns a true or false if it hits something or not, we can store that value in a raycast hit and then check if it’s null or not. To keep things nice and tidy, we can put this in a return type method too. The only difference to the ones we have been using lately is instead of putting void, we put a data type and with this one, it’s a bool.
Now we can cast the ray from the player's position downwards for 1 unity. Next, we can check if the ray collided with anything and if it has (not null) return a true otherwise return false.
lastly, we need to check this before jumping and since it’s a return type function, we can just add it to where we check if the space is pressed.
Now this should work, right?
Sadly no, everything is working perfectly, it’s just picking up the player as a collider. We can fix that by adding in a layer mask.
This does require you to make another layer and changing the ground to that layer.
Now to add the layer mask to the raycast which we can just add onto the end of the one we already have. You can also use 1 << “layer number” so in my case, the ground layer is the 8th layer so I would use 1 << 8.
Now to test it’s working as intended.
Yay finally! There are some downsides to doing it this way but it shows you can check if the player is grounded and limit the jumping to when they are.
As always remember to test everything out and see you in the next one!