NodeJS While循环更新游戏引擎块节点事件循环

rjzwgtxy  于 2023-08-04  发布在  Node.js
关注(0)|答案(1)|浏览(96)

我正在使用Node.js构建一个多人游戏。为了不断更新所有游戏的状态,我执行了以下操作

while (true) {
  for (const game of games) {
    game.update()
  }
}

字符串
这显然会导致节点事件循环被阻塞。什么是正确的技术在这里?
游戏是实时的,因此需要不断更新。

ffx8fchx

ffx8fchx1#

这样,所有的代码都将在主线程中运行,所以如果你用true创建一个while循环,它将完全阻塞主线程。简单的方法是每秒调用更新函数X次。实现这一点的一种方法是:

const FRAMES_PER_SECOND = 20;
    const REFRESH_TIME = 1000/FRAMES_PER_SECOND;
    
    setTimeout(updateGames, REFRESH_TIME):
    
    function updateGames()
    {
      for (const game of games) {
        game.update()
      }
    }

字符串
这种方法应该可以工作,但请注意,它不能很好地扩展多个游戏,因为如果处理时间超过了一帧的分配时间,它将锁定整个应用程序。
解决这个问题的另一种方法是使用Web Workers。您可以使用一个工人池,甚至每个游戏一个工人。
对所有游戏使用一个Web Worker,您可以执行以下操作:

main.js

// Create a new web worker
const worker = new Worker('worker.js');

// Add an event listener to receive messages from the worker
worker.addEventListener('message', (event) => {
  const { games } = event.data;
  console.log('Received updated games from worker:', games);
});

// Function to send a message to the worker to update the games
function updateGames() {
  worker.postMessage('updateGames');
}

// Set a timer to periodically update the games
setInterval(updateGames, REFRESH_TIME);

worker.js

// Initialize the games array
const games = [];

// Function to update the games
function updateGames() {
  for (const game of games) {
    game.update();
  }

  // Send the updated games back to the main script
  self.postMessage({ games });
}

// Event listener to receive messages from the main script
self.addEventListener('message', (event) => {
  const message = event.data;

  if (message === 'updateGames') {
    updateGames();
  }
});


一个更好的方法是使用一个工人池,其中每个工人更新一个游戏。

相关问题