Jump OnCollisionEnter2D

Hello all,

I have been able to prevent infinite jumping by checking if the player is onCloud.
However, I have the problem that the player only has to touch the cloud Collider2D and then immediately jump again.

I would like to prevent this. I want the player to be able to jump only when he is standing on the cloud and not when he just touched it.

What is the best way to do this?

    private void CalculateMovement()
    {

        float moveLeftRight = Input.GetAxis("Horizontal");
        transform.Translate(Vector3.right * moveLeftRight * PlayerSpeed * Time.deltaTime);

        if (Input.GetKeyDown(KeyCode.Space) && onCloud == true)
        {
            myOwnRigidBody.velocity = Vector2.up * JumpHeight;
            onCloud = false;
        }



    }

    private void OnCollisionEnter2D(Collision2D other)
    {
        if (other.gameObject.tag == "Cloud")
        {
            onCloud = true;
        }

    }

The collision callback gives you the collider you hit and the point of contact. You can study that point and compare it to your own point to decide if it is low enough to constitute “standing on it”

Have you considered using PlatformEffector2D? It seems like this would be a case where you would use it, and I haven’t tested it myself, but it should only register collisions from the top.

1 Like

You can also use Rigidbody2D.IsTouching() and provide a ContactFilter2D that is set to filter only collision normals coming from underneath on the cloud layer. All this can be done in a single line of code like this.

Here’s a demonstration and associated project you can load:

1 Like