Is this good practice for calling a random event in a game loop in JS?

22 Views Asked by At

I'm trying to have a function called randomly while my game is running. The function basically generates a cloud that flies across my canvas element for the game I'm making. The event its Here's my attempt:

function gameloop(){
  let r = Math.floor(Math.random*100);
  if(r == 0) createCloud();

  render();
  window.requestGameAnimation.gameloop();
}
1

There are 1 best solutions below

0
scuba_mike On

Depends on how "random" you want the event to occur. For example, if you always want the clouds to fly, but the interval between those events to be random, you could do something like the following:

function flyClouds() {
  //createCloud();
  console.log('Creating Clouds...');

  const delay = Math.floor(Math.random * 1000 * 60) + 1; // 1 second min, 1 minute max
  setTimeout(flyClouds, delay);
}

flyClouds();

If instead you want the clouds to render in probability of something (akin to a lottery), then the code you have currently is probably best.