Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Double jump script not working

Discussion in 'Scripting' started by michaelpynes, Mar 17, 2021.

  1. michaelpynes

    michaelpynes

    Joined:
    Sep 12, 2019
    Posts:
    79
    I am trying to figure out why this is not working. The issue is that the "DoubleJumpUnlocked && Input.GetKeyDown(KeyCode.W) && canDoubleJump" seems to only become true during one frame after pressing the 'W' button. Assume the DoubleJumpUnlocked is true and the canDoubleJump is true when I jump.
    Code (CSharp):
    1. if (isGrounded())
    2.             canDoubleJump = false;
    3.         Debug.Log("Can Jump: " + canDoubleJump);// + " | Unlocked: " + DoubleJumpUnlocked + " | Is it working: " + (DoubleJumpUnlocked && Input.GetKeyDown(KeyCode.W) && canDoubleJump));
    4.  
    5.         if (DoubleJumpUnlocked && Input.GetKeyDown(KeyCode.W) && canDoubleJump)
    6.         {
    7.             Debug.Log("Double Jumped.");
    8.             playerRigid.velocity = new Vector2(0, jumpForce / 2);
    9.             canDoubleJump = false;
    10.         }
    11.         if (isGrounded() && Input.GetKey(KeyCode.W))
    12.         {
    13.             playerRigid.velocity = new Vector2(0, jumpForce);
    14.             canDoubleJump = true;
    15.         }
     
  2. Brathnann

    Brathnann

    Joined:
    Aug 12, 2014
    Posts:
    7,138
    If canDoubleJump is being reset to false, then the error would be in your isGrounded() check since the next frame of what I assume is the Update() method checks for isGrounded() and is probably setting it back to false.

    Edit
    @kdgalla post after mine suggest maybe I don't understand the implementation. I assume for double jump it's tap w to jump once, tap again while in the air for the second jump. I'm not sure if the intention is to allow holding down the w key to have different jump heights.
     
    Last edited: Mar 17, 2021
  3. kdgalla

    kdgalla

    Joined:
    Mar 15, 2013
    Posts:
    4,266
    Yeah, GetKeyDown is only true for one frame after pressing the key. If you want to know whether the use is currently holding the key down, then use GetKey instead of GetKeyDown.
     
    Brathnann likes this.
  4. michaelpynes

    michaelpynes

    Joined:
    Sep 12, 2019
    Posts:
    79
    I'm wanting to double jump after I jump once and am still in the air.