Unity - Checking if the player is grounded not working

I want the player to jump when the player is grounded.

private void OnTriggerStay(Collider other)
{
    if(other.gameObject.layer == 8)
    {
        isGrounded = true;
    }else { isGrounded = false; }
}

The player is on air when spawning. After the player falls to the Terrain, which has the tag Ground, isGrounded is still false. When I set isGrounded manually true and jump again, it's still true after collision. I also don't want the player to double jump in the air, which I probaly already coded but is not working because something is wrong.

Changing OnTriggerStay to OnTriggerEnter doesn't change something. I hope you can help me.


Solution 1:

Do not use OnTriggerStay to do this. That's not guaranteed to be true very time.

Set isGrounded flag to true when OnCollisionEnter is called. Set it to false when OnCollisionExit is called.

bool isGrounded = true;

private float jumpForce = 2f;
private Rigidbody pRigidBody;

void Start()
{
    pRigidBody = GetComponent<Rigidbody>();
}

private void Update()
{
    if (Input.GetButtonDown("Jump") && isGrounded)
    {
        pRigidBody.AddForce(new Vector3(0, jumpForce, 0));
    }
}

void OnCollisionEnter(Collision collision)
{
    Debug.Log("Entered");
    if (collision.gameObject.CompareTag("Ground"))
    {
        isGrounded = true;
    }
}

void OnCollisionExit(Collision collision)
{
    Debug.Log("Exited");
    if (collision.gameObject.CompareTag("Ground"))
    {
        isGrounded = false;
    }
}

Before you say it doesn't work, please check the following:

  • You must have Rigidbody or Rigidbody2D attached to the player.

  • If this Rigidbody2D, you must use OnCollisionEnter2D and OnCollisionExit2D.

  • You must have Collider attached to the player with IsTrigger disabled.

  • Make sure you are not moving the Rigidbody with the transform such as transform.position and transform.Translate. You must move Rigidbody with the MovePosition function.