- Home /
 
Have a delay after each jump, so user cant spam jump
Hello, i was wondering how i could implement a sort of delay into my game so that after the user jumps, they cant immidiately jump straight after. My game is all in the air so i have no onGround or grounded function, and i just need to know how i would make it so that there is a delay in between jumps. I hope it make sense and thank you
My Code:
using UnityEngine; using System.Collections;
public class NewJump : MonoBehaviour {
 public int jumpHeight;
 float jumpSpeed;
 Vector3 velocity;
 
 void Start(){
     jumpSpeed = Mathf.Sqrt(-2*Physics.gravity.y*jumpHeight) + 0.1f;
 }
 
 void Update(){
     if (Input.GetMouseButtonDown(0)){
         velocity = rigidbody.velocity;
         velocity.y = jumpSpeed;
         rigidbody.velocity = velocity;
     }
 }
 
               }
Answer by Mmmpies · Jan 31, 2015 at 08:11 PM
just set a Time.time to a bit in the future like this:
 private float canJump = 0f;
 
 // then in update
 
 if (Input.GetMouseButtonDown(0) && Time.time > canJump){
  
     velocity = rigidbody.velocity;
     velocity.y = jumpSpeed;
     rigidbody.velocity = velocity;
     canJump = Time.time + 1.5f;    // whatever time a jump takes
 }
 
              Answer by Derek-Wong · Feb 01, 2015 at 07:23 AM
or you can simply set a bool
 private bool isJumping;
 
 private void jump(){
   if(!isJumping){
      isJumping = true;
      //jump here
      //reset isJumping after 1.5 sec
      invoke("resetIsJumping", 1.5f);
   }
 }
 
 private void resetIsJumping(){
   isJumping=false;
 }
 
 
              Answer by Shabby91 · Oct 04, 2017 at 09:11 AM
I had used a "timer" to let the addforce work otherwise the character has no time to jump because update start every frame. (timer>5 works fine for me and the delay is 1 sec). This is my code:
 private float jumpDelay=1f;
     public bool jumped;
     public int timer;
 
               //bla bla bla
     void Start () {
         jumped = false;
    
         if (jumpDelay<=0)
         {
             jumpDelay = 1;
         }
     }
 
     private void Update()
     {
         if (grounded && Input.GetAxis("Jump") > 0 && !jumped)
         {
             grounded = false;
             myAnim.SetBool("isGrounded", grounded);
             myRB.AddForce(new Vector2(0, jumpHeight));
             timer += 1;
             if (timer > 5)
                 StartCoroutine(SpamBlockco());
             else
                 jumped = false;
         }
     }
 
     public IEnumerator SpamBlockco()
     {
         jumped = true;
             yield return new WaitForSeconds(jumpDelay);
         
         yield return null;
         jumped = false;
         timer = 0;
     }
 
              Your answer