checking if grounded on rigidbody

i’ve looked through unityAnswers and not found what i’m looking for… like on the FPSWalker script, i need a way to find whether a rigidbody is grounded or not through java…

thanks for your help…

this is in C#

public bool IsGrounded;

void OnCollisionStay (Collision collisionInfo)
{
     IsGrounded = true;
}

void OnCollisionExit (Collision collisionInfo)
{
     IsGrounded = false;
}

this is in Js:

private var IsGrounded = false;

function OnCollisionStay (Collision collisionInfo)
{
	IsGrounded = true;	
}
function OnCollisionExit (Collision collisionInfo)
{
	IsGrounded = false;	
}

edit:
currently i use this:
C#

float GroundDistance;
bool IsGrounded ()
{
	return Physics.Raycast (transform.position, - Vector3.up, GroundDistance + 0.1f);
}

There are several ways for you to detect wheater you are on the ground or not.

SphereCast is generally a good idea.

OnCollisionEnter Can also be used.

I’ve typically done something like this

		public float isGroundedRayLength = 0.1f;
public LayerMask layerMaskForGrounded;
public bool isGrounded {
				get {
						Vector3 position = transform.position;
						position.y = GetComponent<Collider2D>().bounds.min.y + 0.1f;
						float length = isGroundedRayLength + 0.1f;
						Debug.DrawRay (position, Vector3.down * length);
						bool grounded = Physics2D.Raycast (position, Vector3.down, length, layerMaskForGrounded.value);
						return grounded;
				}
		}

This specific example uses 2D physic but just take out the 2D for 3D games. Using the layer mask allows you to ignore certain object like other players or the player themselves. This also uses the colliders lowest point for the y so no matter how tall your object is this will work.

The only issue with this code is if you have a rather wide character and you move onto an edge where your centre is no longer above the ground but the sides are. If this does become an issue, either use sphereCast or boxCast as they will more accurately cover that area, but are more expensive if just a single ray will do.

But what when I for example have racing game?
The map is full of small pieces.
I’ve tried to make variable “IsGrounded” which changes state thanks OnCollisionEnter and Exit, but it wasn’t great idea. When car collides new map element, the variable state is changed to true, but sec later it returns to 0 because last element is lossing collision.
What can I do in this situation?

Another option but it might not be the most efficient is perform a few Raycasts down to the ground and check if they hit anything. I’ve found this more reliable in some situations but again, it could be inefficient if you’re doing lots of them from lots of objects.