# How to prevent OnCollisionEnter2D calling a function again and again?

My current code makes a ball keep jumping whenever it hits the ground. But when it hits a vertical ground it keeps calling the jump function again and again. That is because OnCollisionEnter2D makes the isGrounded bool true as long as it is in touch with a vertical collider. I tried several ways for example this didn't work for me:

void FixedUpdate()
{

if(isGrounded == true){
Verticaljump();
isGrounded = false;
}
}
void OnCollisionEnter2D(Collision2D collision) {
if(collision.gameObject.CompareTag("H-Ground")){
isGrounded = true;
}
}


As shown in the picture the OncollisionEnter2D starts and keep adding force on y-axis.Is there any way I can call a function only once even if the gameObject keeps colliding with a surface.

OnCollisionExit2D also does not work. So how can I call a function only once as it collides with ground and even if it keeps colliding with the ground?

If I've understood your question correctly you have an issue in a situation where the ball touches the "ground" from a side?

Like there (consider = to be ground and o to be a ball)

     o=====

===========


One solution which comes to my mind is to add a small invisible object with rigidbody/collider on the bottom of the ball which will handle isGrounded situation. Then if the rest of the ball touches the ground you just do whatever else you want as grounded situation is already handled by other object (of course you will have to pass that isGrounded to the ball object itself.

Another solution is to check if the transform.position of the platform is actually below the transform.position of the ball. Like that

void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.CompareTag("H-Ground") && (collision.gameObject.transform.position.y < this.transform.position.y))
{
isGrounded = true;
}
}

• The ground checker object doesn't need its own Rigidbody. Just a collider will do, and it can piggyback off of the parent object's body. A short raycast/circle cast is also a popular way to check for ground below only. Searching "Unity ground check" will turn up lots of examples. – DMGregory Feb 2 at 12:56
• @DMGregory thank you for the hint! – Pavel Stepanov Feb 2 at 13:03
• @PavelStepanov I the problem I am facing is a bit complicated to explain. I have edited my question so that it can be correctly understood. – Jacob Frye Feb 2 at 17:42