Timer or homemade game loop?

I use a timer when I do computergames that need constantly upgrades, but in the book “Developing games in java” it shows how to do a homemade gameloop.

The loop would loke something like this:

while(isRunning){
//Update game here
thread.sleep(20);
}

But this way I think the game speed will depend on how fast the updating is.

But what do you guys think is the best solution?

For fast games I prefer to use a timer and calculate the time elapsed since the last update and trigger events after x seconds.
but this method requires a more complex organisation and more computations everywhere. And it uses more CPU, could be a problem with multi threads maybe.


t=system time (let's suppose all times are represented in seconds)
et1=0;   //event 1 is triggered every 0.1 seconds
et2=0;   //event 2 is triggered every 2.5  seconds

while(isRunning)
{
   if (et1>=0.1)
   {
              //fire event 1 
              et1-=0.1; 
                      //if you can afford to loose some calls to event1
                     // in the case your computer is too slow to update every 0.1 seconds ;     you could prefer
                     //et1=et1%0.1; 
                     //if for example you want the player's energy to go down of X points  every 0.1 seconds you should use instead:
                     //a=et/0.1;
                     //et=et%0.1;
                     //energy-=a*X;
   }

//same for event2
   
   //Update rest of the game here

   et1+=system time-t;  
   et2+=system time-t;  
   t=system time;
} 

Well the method you use in that code is using a Timer right?

yes.
Well depends what you mean by “timer”

“thread.sleep(20)” could be considered a timer too.

I mean an instace of the Timer class.

Have a look at GAGETimer. Search for it on the forum if you need more info.

[quote]Well the method you use in that code is using a Timer right?
[/quote]
Use the model/view/controler patern with your 2d games.

Run your controler in a thread and your viewer in another and use some the model to synchronize between the controler and the viewer.

A timer is just an object that will be started in his own thread and send a message to your thread after a certain time.