I'm working on a simple Java 2D game.
I wrote a certain game-loop for the game. Using this game-loop, the game sometimes runs in moderate (constant, I think) speed, and sometimes when I start it, it runs in slow (constant) speed.
I learned to implement this game-loop from the following article: Here
It's code:
(I changed it's code to Java. You can find this loop in the article under the title "FPS dependent on Constant Game Speed").
public void run(){
next_game_tick = System.currentTimeMillis();
while(true){
updateGame(); // This is actually a bunch of methods.
repaint();
next_game_tick = next_game_tick + skip_ticks;
sleep_time = next_game_tick - System.currentTimeMillis();
if(sleep_time<0)sleep_time=2;
try {
Thread.sleep(sleep_time);
} catch (InterruptedException e) {}
next_game_tick = System.currentTimeMillis();
}
}
As I said, this loop wasn't always running the game at an appropriate speed, so I looked at the other game-loop implementations suggested in the above article.
The following implementation, only based on it's description, seemed like the most suitable for my game:
int TICKS_PER_SECOND = 50;
int SKIP_TICKS = 1000 / TICKS_PER_SECOND;
int MAX_FRAMESKIP = 10;
long next_game_tick = System.currentTimeMillis();
int loops;
bool game_is_running = true;
while( game_is_running ) {
loops = 0;
while( System.currentTimeMillis() > next_game_tick && loops < MAX_FRAMESKIP) {
update_game();
next_game_tick += SKIP_TICKS;
loops++;
}
repaint();
}
(I changed it's code to Java. You can find this loop in the article under the title "Constant Game Speed with Maximum FPS").
My problem is, I don't fully understand it. I read it's description in the article, and understood that this game-loop might be the best for my game, but didn't understand fully how it works.
I would appreciate if someone explained this game-loop to me, so I would fully understand it before trying to implement it in my game.
(EDIT: I understand the concept of a game-loop and how it works, but not this game loop specifically and everything it does).
Thank you for your help