I was creating the jumping animation sequences for my player in Unity when suddenly when the game started my code was no longer able to detect whether the character was actually “grounded”. So in loop my character performs the falling animation even if he is on the ground.
I tried checking inside my code through many debug.logs and came to the conclusion that yes, my grounded bool checking functions are executed, but the code fails to enter the raycast condition. Also all of a sudden the onDrawGizmos function stopped drawing everything I put into it.
I thought the problem was a bug in the Physics class so to check I created another script and ran a raycast from it and it worked there.
I really don’t know what the problem could be. Could it be given by an animator setting? Is it a bug?
Well you can relax because I think your code is almost good! This is a common problem with what we call scene queries. I’m assuming you are using Nvidia PhysX for a 3D game, but this is also true for any physics engine, like Box2D in 2D.
There are mainly two types of scene queries proposed by physics engine: casting and overlapping. Casting allows you to project something in the virtual physics world and get data when there is a hit, while overlapping will give you data when an Actor A is overlapping with an Actor B.
In your case, you mentioned using a raycast. Raycasting falls under the casting category of scene queries. For a physics engine to be able to cast a ray, or an actual topology when doing a Sphere/Box/CapsuleCast, it has to be able to detect the other Actors along the sweeping path. This can only be done if the other actors are at least at a DEFAULT_CONTACT_OFFSET distance away from each other.
This value represents the minimum distance that an Actor A must be from an Actor B for a sweep query to detect it. If it is not at least DEFAULT_CONTACT_OFFSET away, then the Actors A and B are considered to be overlapping, and only an overlap query will give data about their interaction.
So if you don’t enter your raycast condition, that means that the physics engine found no Actors along the sweeping path. One way to fix it is to change your sweeping distance if your objects are too far (beyond the sweeping path) or reduce the size of DEFAULT_CONTACT_OFFSET if your objects are too near.
Taking this into consideration, you also need to make sure that once your Player is considered grounded, it is actually DEFAULT_CONTACT_OFFSET away from the ground, at all time. Otherwise next time you re-enter your ground checking algorithm, and any test based on casting queries, it again won’t find any Actors along the sweeping path.