Collision position - Improving on the 'grounded' mechanic


At the moment, my character is able to jump whenever he is 'grounded'. I am setting grounded to true whenever the character collides with an object, using OnCollisionStay. The problem with this is that it means that if the collision with with an object above or to the sides, you are able to jump again meaning you can effectively wall jump endlessly.

What I want to do is fix this so that you are only able to jump when you have ground beneath you, so only on collisions below the character. I have two possible methods for doing this:

1) Constantly cast a ray downwards, and only set grounded to true when the ray contacts some floor.

2) Using the OnCollisionStay, check the location of the collision, ensure it was below you and then allow the player to jump again.

I'm unsure of which method is best, and I have no idea if you can check the location of a collision for number 2.

Can anyone help?

The Raycast seems good to me. Physics.Raycast() returns true or false depending on wether the ray has hit something or not. So if you set up the ray with correct parameters you should be able to use the return value for your grounded variable. Moreover the additional parameter RaycastHitInfo offers plenty of information about the object that was hit, the GameObject for example. Thus you could add poisoned floor and lava or bouncy surfaces to your game quite easyly.

The ray seems like a good idea, except if you want your character to be able to jump when standing more than halfway out on a ledge.

If you want him to be able to do that, I would suggest adding a new collider as trigger under him, slightly smaller than the real collider. You could then use the trigger events to do your game logic.

Oh, and you didn't say anything about whether you are limiting the rays length, but I assume you are, since it wouldn't make much sense otherwise :)