How to Bounce the same height every time

I just wanted to share a helpful tip instead of using the bounce material where your player bounces higher and higher every time. I know when I was following I didn’t want it to make my player go higher and higher because of the level design I had in my head. I wanted 1 constant height every bounce or “mushroom” would do.

Instead of the material, make a new script called Bounce(cleaner code this way imo)
Get rid of the Start and Update code in there and simply put the code below. Make sure to go back into Unity and on your player add the tag Player found in the screenshot below also.

{

[SerializeField] float bounce = 15f;

void OnCollisionEnter2D(Collision2D collision)

{

    if (collision.gameObject.CompareTag("Player"))

    {

        collision.gameObject.GetComponent<Rigidbody2D>().AddForce(Vector2.up * bounce, ForceMode2D.Impulse);

    }

}

}
5 Likes

Simple! Thanks man!

This is great!

I’d like to improve upon it one step further by adding a collision normal that specifies only add force if the player touches the TOP of the collider. I also added a single play animation for jump in there.

    [SerializeField] [Range(1f, 20f)] float bounceForce = 5f;

    private void OnCollisionEnter2D(Collision2D collision)
    {
        
        
        if (collision.gameObject.CompareTag("Player") && collision.contacts[0].normal.y < -0.5f)
        {
            collision.gameObject.GetComponent<Rigidbody2D>().AddForce(Vector2.up * bounceForce, ForceMode2D.Impulse);
            collision.gameObject.GetComponent<Animator>().SetTrigger("pressedJump");
        }
    }

Basically the second criteria is saying, take the collision’s first contact (array position 0) and check the coordinates (.normal) of the y axis (.y). The top of a collider is negative. So anything less than -0.5 should count as the collider’s head or top.

If you want to check for different collision.normal points, try throwing something out to the console with a Debug.Log(collision.contacts[0].normal); This will throw the coordinate contacts out to the console so you can check where you are colliding.

Of note: make sure it’s .contactS with an s not just .contact.

Edit: I also made the bounceForce float a range to prevent launching the player off into space lol.

Privacy & Terms