0

I'm making a game in C++ using Box2D and WebSocket++. The world needs to updated every 1/60 second. Meanwhile the WebSocket server handles players. How I should make the interval? I know there's no setInterval function in C++, but I can do something like this:

• make async function - https://stackoverflow.com/questions/33234403/using-setinterval-in-c/33234557

• make async thread - https://codereview.stackexchange.com/questions/40915/simple-multithread-timer

or maybe there's a lib?

Note: this isn't a duplicate of How should I write a main game loop? because here I need asynchronous game loop. In linked topic there are synchronous game loops.

Why I won't use while (sync loop):

  • commands after while (loop) are never excuted if loop is set to true.

1 Answers1

1

It looks you fell into "I need this!" scheme. But all you need is just call some specific part of game loop asynchronously or non-blocking.

How to achieve this? Make sure whole loop is executed 60 times every second. In more proper words: Make sure every iteration takes less than 16.(6) ms. If it takes longer (your loop "lagged"), make two (or more) updates next frame, so the average FPS remains constant. In the loop gather user input, network data, update game state, render. With this, you can have another thread running WebSocket or a non-blocking function that checks whether anything is in network buffer to read. If not, it returns immediately.

Anything past the while loop is... not a game anymore. Make some cleanup there or anything you find appropriate. Loop might take some bool isRunning as condition and be handled inside.

Mars
  • 233
  • 1
  • 10