I making a game and I want to call a function that runs every random second to spawn something every time. I've seen some posts that said to use the setInterval()
function to keep track of the time but I don't know where to implement it because I'm using the requestAnimationFrame()
to loop the game. I also tried to implement it in the update function of the classes but it doesn't seem to work.
This is my main with the loop
import Game from '/src/game.js';
let canvas = document.getElementById('main');
let ctx = canvas.getContext('2d');
const WIDTH_SCREEN = 800;
const HEIGTH_SCREEN = 600;
let game = new Game(WIDTH_SCREEN, HEIGTH_SCREEN);
game.start();
function loop() {
ctx.clearRect(0, 0, WIDTH_SCREEN, HEIGTH_SCREEN);
game.update(ctx);
requestAnimationFrame(loop);
}
window.addEventListener("keydown", (event) => game.controller.keyListener(event));
window.addEventListener("keyup", (event) => game.controller.keyListener(event));
requestAnimationFrame(loop);