We have grounding problems, time to fix it!

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!

Game Developer in the making~

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

API Management Tech Talk 13th May 2021

How Database Indexing Works…

How to Migrate the Sakila Database from MongoDB to Distributed SQL with Studio 3T

2 minute guide to pd.groupby(…).first() & pd.groupby(…).last()

Linking to SQL Server Date Fields from Microsoft Access

Development Team, the marginalized role when adopting Scrum

Updates on Fleta Connect (November 2nd, 2021)

Virtual Environments

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
Rose Owen

Rose Owen

Game Developer in the making~

More from Medium

Galaxy Shooter 2D — Boss (Set up)

Previsualization in Unity (Game Dev Day 52)

VR in Unity: Pt 03- VR Dev Series 03

Script communication in unity using GetComponent: