Code Example for Detecting if b2Body is Resting On Top?

Diggsey wrote:
Or you could loop through all the contacts, and if the collision normal is pointing up, then the player is on the ground 😉


I'm using code like this right now, and it seemed to be working fine. But I'm playing with performance and finding a strange issue. If I turn iterations down to 1 and stack two boxes on top of each other, my character no longer detects the second stacked box as "ground" -- but it does detect a single box as "ground".

Looking at the collision normals I'm only ever seeing positive normals, whereas when I'm touching the ground I see a negative normal (gravity pushing me into the ground and the ground pushing me back out).

Is the collision normal local to either of the shapes, i.e. shape1 vs. shape2, or is it in world space?

Instead of checking the normal, I could just check if the collision is occurring on the bottom edge of the player's shape (box)... is there a straight forward way to get that info from the contact?
The collision normal is in world space. It should point from shape1 to shape2. If not then it's a bug.

I forget how I determine which shape is shape1 and which is shape2. But you should probably assume it's arbitrary and that it can change each time two shapes start touching.
So, to fix my code I now check whether my character is shape1 or shape2. If he's shape1 and the collision normal is positive he's "on the ground." If he's shape2 and the collision normal is negative, he's on the ground. Of course, I'm checking the y-component of the collision normal.
For more accurate results, you could use atan2() to get an angle and check if it's within predefined ranges.

Original thread: https://box2d.org/forum/viewtopic.php?t=187