Currently I have the code create a bullet 60 times per second (setInterval) I have tried for loops but the did not work at all. Does any one have an idea how can I regulate the fire rate?
Thanks.
Currently I have the code create a bullet 60 times per second (setInterval) I have tried for loops but the did not work at all. Does any one have an idea how can I regulate the fire rate?
Thanks.
In most real time games you would have a main loop that you control your animations from. You would add the fire control to this.
// object to hold details about the gun
const gun = {
fireRate : 2, // in frames (if 60 frames a second 2 would be 30 times a second
nextShotIn : 0, // count down timer till next shot
update() { // call every frame
if(this.nextShotIn > 0){
this.nextShotIn -= 1;
}
},
fire(){
if(this.nextShotIn === 0){
// call function to fire a bullet
this.nextShotIn = this.fireRate; // set the countdown timer
}
}
}
function mainAnimationLoop()
// game code
gun.update();
if(fireButtonDown){
gun.fire(); // fire the gun. Will only fire at the max rate you set with fireRate
}
// rest of game code
}