I've read some stuff about game loops, but I can't seem to find out what the objectively best is, though I feel like there should be such a thing as a best game loop.
I'm going to semi-answer my own question here by going over some examples. The game loop I'm looking for should have the most effective way of updating the gamestate and calculating, while listening for input. When things get language specific, assume I'm using Java.
So, the most basic game loop seems to be this:
while(running){
update();
render();
}
However, this will make the program work differently on different computers, something not often desired. So to fix this I usually see one of the following two solutions:
//Fix the timestep
double step = 1/60;
double time;
while(running){
update(step);
render();
try {
Thread.sleep(Math.max(0,step + (time - (time = System.currentTimeMillis()) / 1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
Or
//Vary the timestep
double time;
while(running){
update(-time + (time = System.currentTimeMillis()) / 1000));
render();
}
I tend to go with the second option, but then we are faced with an issue: we are rendering a lot more often than needed. So what I've done is kept this loop, but only render if timeSinceLastUpdate >= 1/60
.
However, optimally we would rather have the rendering and the updating process completely freed from each other, so I've thought about multithreading, where I have one thread that gets an optimal amount of calculations per second (determined by how many the PC can handle, at how many calculations per second calculations are accurate, and others), and one thread that's locked to a certain amount of frames per second that displays the game based on the last gamestate. But this creates another issue: the data that describes a gamestate is under constant modification. So I save the last gamestate, construct another, and then make that the saved gamestate when it's done and construct another again, and so forth. However, this means I'm constantly creating new data rather than changing existing data, which may be more work for the computer.
So what's the most effective kind of gameloop? I'm mainly interested in whether computing a completely new gamestate rather than changing the gamestate will make a big difference