0

Trying to delay shooting in a game, the action is done by clicking but currently, it shots every frame while holding click.

SetTimeInterval does not work in my case since it just loops the function SetTimeout does not work as well because it stops the function the second it's played and after the interval. Tried a sleep function but it freezes up the code while running

//sleepcode
var sleep = function(delay) {
    var start = new Date().getTime();
    while (new Date().getTime() < start + delay);
} 
//called by:
if(self.pressingAttack){
    self.shootBullet(self.mouseAngle);
    sleep(3000);
}

I want a function that shots the second its clicked but delays the second bullets, similar to every shooting game ever.

Sami Ahmed Siddiqui
  • 2,328
  • 1
  • 16
  • 29
xRegency
  • 45
  • 7
  • how many frames you want to delay it. then count the frames from shoot frame and dont let it to it in the if statment – Andam May 30 '19 at 06:06

2 Answers2

0

You cannot do what you want the way you want it. JavaScript is designed not to have "a sleep function".

From what you said it seems you have a check inside an animation frame handler that tests whether a button is pressed, and to trigger an action if it is. In order to prevent this action from triggering for the next three seconds, simply check if it has been three seconds since the action last triggered:

let lastAttack = null;

// ...

if (self.pressingAttack) {
    let now = new Date();
    if (!lastAttack || now - lastAttack > 3000) {
      self.shootBullet(self.mouseAngle);
      lastAttack = now;
    }
}
Amadan
  • 191,408
  • 23
  • 240
  • 301
  • what is now exactly? – xRegency May 30 '19 at 06:21
  • A variable initialised with the current time, `new Date()`. – Amadan May 30 '19 at 06:22
  • any difference between var and let? – xRegency May 30 '19 at 06:25
  • See [What's the difference between using “let” and “var”?](https://stackoverflow.com/questions/762011/whats-the-difference-between-using-let-and-var) Basically, there's almost no reason to use `var` any more, as `let` was created to patch up some bad properties of `var`. `var` still exists mostly just so old code wouldn't break. – Amadan May 30 '19 at 06:26
0

You must use promises for "sleep".

function sleep(ms) {
  return new Promise(resolve => setTimeout(resolve, ms));
}

And to use the promise to wait, IE use await, you can only do that in an async function. It should also be noted that you do not want this in your main game loop because the code will stop and wait ... so your main loop needs to call the attack loop and not wait for it.

async function Attackloop() {

// some code

     while (self.pressingAttack) {
         self.shootBullet(self.mouseAngle);
         await sleep(3000);
     }

// some code.

}
Wayne
  • 4,760
  • 1
  • 24
  • 24