[size=10pt][size=10pt][size=10pt][size=10pt]Generally,the game loop is built up manually,hower, in my opioin, the game application under awt or swing doesn’t need to do this ,since we can override the defult method Update() with game logic (sprite move and collosion detect ,etc) and Paint() with code of graphic rendering ,and finally we just call Repaint() iteratively within a dead loop while(){} .
so, what’s the [color=blue]necessity of constructing a game loop [/color] by ourself?[/size][/size][/size][/size]
Essentially, calling Repaint() adds a repaint request to the event queue and there is no notion of how long it remains in the queue before repaint is actually executed. Sometimes repaint requests may even be skipped or delayed.
Because Repaint() is at the mercy of the JVM, it is difficult to accurately control the timing of your game. In particular, we have no idea how long we should sleep for, which means we won’t be able to maintain a consistent FPS.
Writing your own game loop is necessary because we don’t know when repaint is actually completed. So, in order accurately control the timing of the game, we must take things into our own hands instead of overriding Update and Paint. The technique involves actively rendering our buffer image to the screen and implementing our own update method. This way we can measure the rendering time and accurately control how long to sleep.
Thanks a lot! There is another question: Is it the absolute way to create a thread handling the game loop seperately? other words, could I make the game loop without using thread programming?
Hsaka’s right, what he describes is sometimes called active rendering while your approach is passive rendering.
About threading, your code has to run in some thread, so you may as well make your own thread to do it in.
The trouble is, if you’re using the AWT to listen for key and mouse events then you need to watch out since the keyPressed(KeyEvent e) etc methods run on the AWT event thread (also called the Event Dispatch Thread, EDT). So you often need to be careful not to modify game code from the EDT while it is running in your own game loop thread. I avoid this by storing the events recieved on the EDT, and then getting them in a synchronized way and processing them on the game loop thread.