How do I check if a character is touching the ground in Unity 2D?

  • 0
    I am making a game for android on Unity 2D. I have a character jump code:
    public void Jump(bool isJump)
        {
            isJump = groundCheck;
    
            if (groundCheck)
            {
                rb2d.velocity = new Vector2(rb2d.velocity.x, jumpPower);
            }
    
        }

    I tried to check if the character is on the ground in this way:
    void OnCollisionEnter(Collision collision)
        {
            if (collision.gameObject.tag == "ground")
            {
               groundCheck = true;
           }
        }

    But that doesn't work at all. How can I make it so that the character can only jump if he is standing on the ground.
    I'm new to C # programming, please help.
    Unity Game Engine Anastasia Armstrong, Apr 5, 2020

  • 1 Answers
  • 0
    Most likely it does not work because initially the variable groundCheck is equal to false in the declaration, you must set it immediately true , because initially the character is already on the ground :

    bool groundCheck = true;

    And after the jump, immediately change to false :

    if (groundCheck)
    {
    rb2d.velocity = new Vector2(rb2d.velocity.x, jumpPower);
    groundCheck = false;
    }
    Anonymous

Your Answer
To place the code, please use CodePen or similar tool. Thanks you!