How can i check if my rigidbody player is grounded

How can I check if my Rigidbody player is grounded?

public class PlayerController : MonoBehaviour
{
    public float speed = 5;
    public float jumpSpeed = 2;
    private float horizontalInput;
    private float verticalInput;
  
    // Update is called once per frame
    void Update()
    {
        horizontalInput = Input.GetAxis("Horizontal");
        verticalInput = Input.GetAxis("Vertical");
  
        transform.Translate(Vector3.right * Time.deltaTime * speed * horizontalInput);
        transform.Translate(Vector3.forward * Time.deltaTime * speed * verticalInput);
  
        if (Input.GetKeyDown (KeyCode.Space) )
        {
            GetComponent<Rigidbody>().velocity += jumpSpeed * Vector3.up;
        }
    }
}
1 Like

There are a few ways to check if a Rigidbody player is grounded in Unity, here are a few examples:

Using Raycasting: You can cast a ray downward from the player’s position and check if it hits a Collider. If it does, the player is considered to be grounded.

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

Using Collision Detection: You can check if the player’s rigidbody is currently in contact with another collider.

bool IsGrounded()
{
    return GetComponent<Rigidbody>().velocity.y == 0;
}

or using Spherecast…there are lots of tutorials on youtube. Did you try there. Accept it as an answer, if it works!

Please be wary that at the apex of a jump, your y velocity briefly becomes 0. This can cause unwanted behaviour.

bool IsGrounded()
{
    float GroundedDistance = 2f;
    rb = GetComponent<RigidBody>();
    if (rb.velocity.y == 0){
        return Physics.Raycast(transform.position, Vector3.down, out RaycastHit hit, GroundedDistance);
}

This will make sure you can only jump if you’re not midair AND you have something solid underneath. You can play with the GroundedDistance variable to meet your needs.

I’d recommend spherecasting over raycasting but it’s up to you.

thanks you

umm yknow this post is from january 2023, i know that by now but thanks anyway