0
\$\begingroup\$

I am using the following Jump script. As I understand it, as soon as I jump it should detect that I'm not grounded and therefore prevent me from jumping again.

However, I am seeing in the Inspector that when I jump, "IsGrounded" remains checked, and only unchecks when I double-jump. Why might this be? I have the capsule collider the exact height of the character and the collider is definitely leaving the ground upon First jump.

using UnityEngine;
using System.Collections;

[RequireComponent(typeof(Rigidbody))]
public class Movement : MonoBehaviour
{
    public Vector3 jump;
    public float jumpForce = 2.0f;

    public bool isGrounded;
    Rigidbody rb;
    void Start()
    {
        rb = GetComponent<Rigidbody>();
        jump = new Vector3(0.0f, 2.0f, 0.0f);
    }

    void OnCollisionStay()
    {
        isGrounded = true;
    }

    void LateUpdate()
    {
        if (Input.GetKeyDown(KeyCode.Space) && isGrounded)
        {

            rb.AddForce(jump * jumpForce, ForceMode.Impulse);
            isGrounded = false;
        }
    }
}
\$\endgroup\$
3
  • 1
    \$\begingroup\$ I note that your OnCollisionStay method does absolutely no checking regarding what the object is colliding with. That's usually not a good idea because you can often have collisions you didn't think about. \$\endgroup\$
    – Philipp
    Jul 2 '21 at 7:04
  • 1
    \$\begingroup\$ And then there is a different problem: You are not checking how you are colliding. Usually you only want the player to be considered grounded when they hit a solid platform from above. Not when they hit a platform from below. \$\endgroup\$
    – Philipp
    Jul 2 '21 at 7:07
  • 1
    \$\begingroup\$ And the third problem: the player will still be considered grounded when they leave the ground for another reason than jumping. Like walking off a platform, or the platform disappearing. \$\endgroup\$
    – Philipp
    Jul 2 '21 at 7:09

Browse other questions tagged .