coroutine waiting for 2D jumping

hi thanks for the help, i watched the live training 2d about movement and jumping in unity and do the jumping stuff already but when the player jumps a few times suddenly he jumps to high, i read that the way to prevent this situation is to do the jump and then make the character wait a few seconds until he can do a jump again, so i tried with StartCoroutine this is the code:

////Jump Button
       
        if (grounded && Input.GetButton ("Jump")) {
           
            StartCoroutine("Jumping");
           
        }

IEnumerator Jumping(){
       


        GetComponent<Rigidbody2D> ().AddForce (new Vector2 (0, jumpForce));
       
        anim.SetBool ("Ground", false);

        yield return new WaitForSeconds (2);


       
       
    }

I have the If statement in the FixedUpdate area. It does the jump but is not stopping any seconds it keeps continually.

Thank you

I would make a bool for checking if you can jump.

For example

bool canjump = true;

then you would just add these two lines in that I’ve commented placement.

canjump = false //Line 14

yield return new WaitForSeconds(2);

canjump = true //On Line 18

Finally, You would check the canjump bool in your jump if statement, This is the best I can make out, as I’m not sure of any other code you have, but this is a quick fix regardless =)

1 Like

Hi again, i tried what you said later and it worked, thanks a lot for the comments this is the code for he If statement:

if (canJump) {
               
            if (grounded && Input.GetButton ("Jump")){

                StartCoroutine ("Jumping");

           
        }

and the Coroutine:

IEnumerator Jumping(){

        canJump = true;

        GetComponent<Rigidbody2D> ().velocity = (new Vector2 (GetComponent<Rigidbody2D>().velocity.x, 0f));

        GetComponent<Rigidbody2D> ().AddForce (new Vector2 (0f, jumpForce));

        canJump = false;

        anim.SetBool ("Ground", false);

        yield return new WaitForSeconds(0.6f);

        canJump = true;
       



    }

thank you

1 Like