We have grounding problems, time to fix it!

Objective: Fixing the issues with the raycasting for IsGrounded.

Rose Owen
3 min readAug 7, 2021

In the last article, found here, we used raycasting to check if the player is grounded. This worked but some problems had come from using a single raycast in the middle.

On the ground but can’t jump because the raycast is off the ledge.

Another problem you might encounter is if you are going down a hill, there is a chance that the raycast won't hit either. This is worse if you make it so the player can only move if they are grounded. With the hill at least you can just increase the distance you check for the ground but the ledge, that won’t work.

One thing we can do is instead of having just 1 ray cast, use 2 and have them check at the ends of the box collider.

Don’t push those bounds too much lol.

But then the code starts to look clunky…

Yes, there are better ways to get the side of the collider, this is just for show.

When looking around for a fix I came across another type of ray cast called a box cast, it projects a box from the player instead of the line. This makes it look a lot cleaner.

Casting the box is almost the same as the ray cast, just have to change the Physics2D.Raycast to Physics2D.BoxCast, add in a measure for the size of the box and a rotation.

Here I’m using the box collider 2D’s center and size to give the box cast its shape and size. You will need to reference the box collider 2D on the player and as always, null check!

With that, we get something like this.

Which if you have some rocky ground it will be fine, whereas drawing 2 rays down each side, you might get stuck on top, like a car trying to go over a bump.

And with that I’ll leave ya to it, I’m sure someone will be by soon to help you off that hill.

It really is amazing how with unity, you can face a problem thinking “but this is how it should be done” and finding many other ways that get the same result and sometimes even better. It kind of makes you think how else can I do this that could work better for me. See you in the next one!

--

--