I am making a 2D canvas game in JavaScript. I am trying to make the enemies shoot a bullet every 3 seconds.
for (var i = 0; i < enemyBullets.length; i++) {
enemyBullets[i].show();
enemyBullets[i].move();
}
// With this loop, whenever there is a bullet added to
// the array , it gets drawn on the canvas and updated.
function Enemy(x, y) {
this.shoot = function(){
var ebullet = new enemyBullet(this.x, this.y);
enemyBullets.push(ebullet);
// Here I have the enemy object and the function
// which adds the bullet to the array.
}
}
Here is how I use the enemy.shoot function in the draw() function, which is called via requestAnimationFrame():
function lol(){
for(var v = 0; v<enemies.length;v++){
enemies[v].shoot();
}
}
setTimeout(lol,3000); // This is what I've tried so far
When I do this, the enemies are not shooting a single bullet every 3 seconds as desired. Instead, 3 seconds after the beginning of the program, they start adding infinite bullets to the array and I don't know how to handle it.