0

Just wondering, is there a specific reason to use a while loop as the game loop. Or could I use another method, like this one.

Note: this is not proper code, and has not been tested. This is just a general idea. This example is also not consistent to a specific coding language, but may follow mostly JavaScript because that's the coding language I know off the top of my head. I've actually tried something similar to this in dart (google flutter).

var startTime;
var running = false;

function loop1(){
  startTime = system.currentMillis();
  loop2();
}

loop2(){
  gameUpdate();
  //ignore my math, I did not focus on doing that property
  //this is just an example and is not proper math
  var delay = 1000 / (system.currentMillis() - startTime);
  setTimeout(loop3, delay);
}

loop3(){
  if(running){
    loop1();
  }
}

edit: could using something like this to avoid the need to use sleep(); be helpful to performance? (or phone battery)

SwiftNinjaPro
  • 117
  • 1
  • 7
  • Your example code is quite JavaScript specific with its use of `setTimeout` so I added a language tag. – John Kugelman Oct 14 '19 at 02:51
  • Sure, in fact if I were to make a game loop I'd do so with a timer set according to my frame rate. – ChiefTwoPencils Oct 14 '19 at 02:52
  • It would be problematic to use `while` as a game loop in JavaScript unless inside an `async` function to stop it blocking. See [Anatomy of a video game](https://developer.mozilla.org/en-US/docs/Games/Anatomy) on MDN for discussion of HTML game loops. – traktor Oct 14 '19 at 03:37

1 Answers1

3

It is perfectly possible to use your code as a main game loop. The reason why a while is preferred is because a main game loop executes endlessly until aborted, this is done simply with while (true) and aborting somewhere inside with break, or with while (abort == false) and setting abort = true somewhere inside. Notice that other loop variants such as for and do-while are more verbose, unless your language let's you do for (;;). Also note that you can restructure your proposed loop to a more simpler version using a while loop.

Javier Silva Ortíz
  • 2,864
  • 1
  • 12
  • 21