After reading Java for Dummies and understanding the fundamentals of programming, I’ve wanted to move onto to game making. After a bit of looking around for tutorials, I have found that there are 20,000 ways to program the animation loop, some work, some don’t, some suck, others don’t, and I can’t quite decide what’s going to be best for me. I’ve read some tutorials, but with everyone disagreeing on the subject, it’s hard to form a basis. So how do people on this forum program the basic animation loop for their games?
The following is from the article link in the previous post.
[quote]example code of the game loop in it’s most simplest form:
bool game_is_running = true;
while( game_is_running ) {
update_game();
display_game();
}
The problem with this simple loop is that it doesn’t handle time, the game just runs.
[/quote]
I’m in a minority, but I think an entirely reasonable alternative is to consider using a single java.util.Timer to run the game loop. It’s not that hard to set up an “Observer” design pattern to subscribe and unsubscribe all objects or processes that need animation ticks. I started an example in the Tutorials section but haven’t had time to make the revisions to put it in an easier-to-read format. One big plus: new loops start at regular intervals without any need to further manage the amount of code that runs within each animation cycle (as long as you don’t try to animate 10,000 objects and start overshooting the cycle time). Seems to scale well.
If you don’t want to deal with the Observer pattern, this is even simpler, and gives a steady 40 updates a second (well actually a little less, but still reasonably steady):
Timer timer = new Timer();
timer.schedule(new RemindTask(), 25, 25);
and
class RemindTask() extends TimerTask {
public void Run() {
updateGame();
yourJPanelOrWhatever.repaint();
}
}
It’s not that hard to set it up so that you can turn the Timer on or off as needed. And the repaints occur often enough you probably won’t need to add any more of them to the response code for the various listeners.