Allan
Allan

Reputation: 11

How do you make a short delay after "keyWentDown" function, so spamming isn't allowed.?

I'm struggling on my code.org platform on how to make a delay, as I'm making a shooter game. When I click I want there to be some sort of reloading happening, so it could take me at least 3000ms to reload.

I heard some things about the timeOut() function, but I'm not sure how to use it. I tried many ways, like keeping the timeout outside the if, and inside the if.

Upvotes: 1

Views: 51

Answers (1)

Cengiz
Cengiz

Reputation: 302

You can use built-in setTimeOut function. As the docs says, it fires the function after the desired time ends. Here I build simple reload functionality for you, space to shoot, a to reload;

var bullets=6;
function draw() {
 
   if(bullets > 0) { 
     if (keyWentDown("space")){
      bullets=bullets-1
      console.log(bullets)
      }}
    if(bullets < 6){
      if(keyWentDown("a")){
        reload();
        
      }
    }  
      
}

function reload(){
  console.log('reloading')
  setTimeout(function() {
  console.log("relaoded");
  bullets = 6;
}, 3000);
}

Here's the Game Lab link; https://studio.code.org/projects/gamelab/ZyXRGRq5hyqcPXYTwcfAPfDihSHCyv1CesSnMBwjMWs

Upvotes: 0

Related Questions