Different kind of game loops in java
I have searched around and come across different kind of game loops. I
have always used
Screen.java that extends JFrame, with also adds all the listeneres which
is normally in two diffrent .java one for keyboard, one for mouse.
public void Draw(Graphics g){
Graphics2D g2 = (Graphics2D)g;
//Everything that I render at the screen goes here, or I pass along g2
to them so they can be rendered. Such as level.draw(g2);
repaint();
}
@Override
public void paint(Graphics g){
Image offScreenBuffer = createImage(getWidth(), getHeight());
Draw(offScreenBuffer.getGraphics());
g.drawImage(offScreenBuffer, 0, 0, null);
}
And then in the main I have a normal Runnable loop with sleep
@Override
public void run(){
while(true){
//all update code goes here.
try{ Thread.sleep(1); }catch(Exception e){}
}
}
But i have seen people recommending using Timer, Semaphore, and TimerTask
to create a run loop that takes care of the input, update, and lastly
reneder. so I wounder which method is best? for it seams if I use
TimerTask's to create the loop that render the game it seams that i need
to lock it to a certain fps.
For what I have seen and understood I can use Timer and TimerTask to
schedule the game updates. But else I don't how I need to change my code
that much, or am I missing something here?
No comments:
Post a Comment