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.