Collision problem on slope

I have a 2D platform game with a character that must jump when the spacebar key is hit. The character should not jump if it is already jumping until it gets back to the gound. I am using OnCollisionStay2D and OnCollisionExit2D to control this behavior. I am using the variable “blnGrounded” (initially set to true) to detect if it is making contact with a platform as shown in the code below.

    // -------------------------------------------------------
    // Horse jumps.
    // -------------------------------------------------------
    public void HorseJumpKeys()
    {
        if (Input.GetKeyDown (KeyCode.Space) && blnGrounded)
        {
            rigidbody2D.AddForce (new Vector2 (0, 750f));
        }
    }

    // -------------------------------------------------------
    // Horse jumps only once.
    // -------------------------------------------------------
    void OnCollisionStay2D(Collision2D coll)
    {
        if (coll.gameObject.tag == "Platform")
        {
            Debug.Log ("OnCollisionStay");
            blnGrounded = true;
        }
    }

    // -------------------------------------------------------
    // Horse jumps only once.
    // -------------------------------------------------------
    void OnCollisionExit2D(Collision2D coll)
    {
        if (coll.gameObject.tag == "Platform")
        {
            Debug.Log ("OnCollisionExit");
            blnGrounded = false;
        }
    }

The code is actually working fine except in an inclined platform when the character is walking down the slope. As you can see in the code I am displaying the event that is currently taking place (OnCollisionStay2D and OnCollisionExit2D) and, when the character is going up the slope, “OnCollisionStay2D” is displayed; but when the character is going down the slope, “OnCollisionExit2D” is displayed.

I will very much appreciate any help.

Well, if you are moving down the slope your character is probably losing contact with the ground for a short while before gravity pulls it down again. When you add a horizontal force, you will propel the character away from the slope which makes it lose contact for a short while.

Anyhow, I’ve always found OnCollisionExit2D to be a bit flakey. It is probably better to use Physics2D.Raycast to see if there is anything below the character.

Problem solved !!!
I can see that Raycast is an excellent option if I need to detect “continuous” contact with a surface.

Thank you PGJ.