Answers for "how to code double jump in unity"

3

double jump script unity

There are a lot of ways to implement the "double jump" feature. The most straight forward would be this one:

public int maxJumps = 2;

private int jumps;
private float jumpForce = 5f;

void Update()
{
    if(Input.GetKeyDown(KeyCode.Space) || Input.GetKeyDown(KeyCode.W))
    {
        this.Jump ();
    }
}

private void Jump()
{
    if (jumps > 0)
    {
        gameObject.GetComponent<Rigidbody2D> ().AddForce (new Vector2 (0, jumpForce), ForcMode2D.Impulse);
        grounded = false;
        jumps = jumps - 1;
    }
    if (jumps == 0)
    {
        return;
    }
}
void OnCollisionEnter2D(Collision2D collider)
{
    if(collider.gameObject.tag == "Ground")
    {
        jumps = maxJumps;
        grounded = true;
        movespeed = 2.0F;                                                            
     }                                                                                
 }
Note that you could have another bool field in order to check if the player has already jumped twice, but using an integer gives you a more flexible solution in case you want to change the game design in the future (ex: letting the user jump three times when using a power-up).

Hope this helps!
Posted by: Guest on March-20-2021

Browse Popular Code Answers by Language