这是在 JS 的游戏循环中调用随机事件的好习惯吗?

问题描述 投票:0回答:1

我正在尝试在游戏运行时随机调用一个函数。该函数基本上为我正在制作的游戏生成一个飞过我的画布元素的云。这是我的尝试:

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

  render();
  window.requestGameAnimation.gameloop();
}
javascript graphics game-loop
1个回答
0
投票

取决于您希望事件发生的“随机性”程度。例如,如果您总是希望云朵飞翔,但这些事件之间的间隔是随机的,您可以执行如下操作:

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();

如果您希望云以某种概率呈现(类似于彩票),那么您当前拥有的代码可能是最好的。

© www.soinside.com 2019 - 2024. All rights reserved.