so I am making a 2d canvas game in Javascript and I want the enemy mobs to shoot a bullet every let's say 3 seconds. I'm almost done with the code , i made everything i just don't know how to make the function repeat.
//this is the enemy object
function Enemy(x, y){
this.sprite = enemySprite;
this.x = x;
this.y = y;
this.shooting = function(){
while(enemyBullets <= bulletsPerTick){
var enemybullet = new enemyBullet(this.x , this.y);
enemyBullets.push(enemybullet);//i'm adding the bullet object to an array .
}
for(var i = 0; i<enemyBullets.length;i++){
enemyBullets[i].show();
enemyBullets[i].move();//if there is an element in the array , draw and update the bullet.
}
}// i left only the important elements of the object needed to answer my question
//this is the enemy bullet object
function enemyBullet(x, y) {
this.x1 = x;
this.y1 = y;
this.r = 5;
this.show = function ()
ctx.beginPath();
ctx.arc(this.x1, this.y1, this.r, 0, Math.PI * 2);
ctx.fillStyle = "black";
ctx.fill();
ctx.closePath()//drawing the bullet
}
this.move = function () {
this.x1 = this.x1 - 5;//updating the bullet
}
In my main file , i have a function draw() which is in requestAnimationFrame(draw):
for (var j = 0; j < enemies.length; j++) {
enemies[j].show();//here i spawn the enemy sprite
enemies[j].shooting();//this is the function which adds the bullets to the array , draws them and updates them.
}
Basically , when i press the start the program now , only one bullet flies and disappears and i want that process to continue over and over again every few seconds , let's say 3 seconds for example , i tried to add enemies[j].shooting() in an interval and timeout but they are in draw, which is in requestAnimationFrame and it doesn't seem to work , if anyone have any clue how to help me I want every advice possible. Also if you need more information about the problem , let me know.