Double & Triple Jump In Unity (Complete Script)

Table of Contents

Double & Triple Jump In Unity (Complete Script)

Reading Time: < 1 minute

Help Others Learn Game Development

Share on facebook
Share on twitter
Share on reddit
Share on linkedin

The script below is ready to go, you can copy/paste it in your project and the game object you attach it to will be able to double and triple jump.

Keep in mind that the object needs to have a BoxCollider2D component attached on him and a Rigidbody2D component.

You also need to tag the game object that increases jump count with the appropriate tag.

				
					public class Player : MonoBehavior
{

    [SerializeField]
    private float jumpForce = 10f;

    private Rigidbody2D myBody;

    // set the appropriate layer mask for the ground in the inspector
    [SerializeField]
    private LayerMask groundLayer;

    // add an empty game object at the feet of the player object
    [SerializeField]
    private Transform groundCheckPos;

    private BoxCollider2D boxCol2D;

    private bool canJump, doubleJump;

    private void Awake()
    {
        myBody = GetComponent<Rigidbody2D>();
        boxCol2D = GetComponent<BoxCollider2D>();
    }

    private void Update()
    {
        IsGrounded();
        HandleJumping();
    }

    void IsGrounded()
    {
        canJump = Physics2D.BoxCast(boxCol2D.bounds.center,
            boxCol2D.bounds.size, 0f, Vector2.down, 0.1f, groundLayer);
    }

    void HandleJumping()
    {
        if (Input.GetButtonDown("Jump"))
        {
            if (canJump)
            {
                doubleJump = true;
                myBody.velocity = new Vector2(myBody.velocity.x, jumpForce);
            }
            else if (doubleJump)
            {
                doubleJump = false;
                myBody.velocity = new Vector2(myBody.velocity.x, jumpForce);
            }
        }
    }

    private void OnTriggerEnter2D(Collider2D collision)
    {
        // use your tag here
        if (collision.CompareTag("Power"))
        {
            collision.gameObject.SetActive(false);
            doubleJump = true;
        }
    }
}