My apologies, I was thinking about something else here. Yes, the logic is called from the Thread which handles updating/rendering/drawing.
Have a look at this:
Here’s a simple game loop:
START
|
INITIALIZE
|
[loop]<-----.
| |
logic |
| |
draw objects |
| |
[finished?]---^ no
|
| yes
CLEANUP
|
EXIT
To control the FPS you need to know how much time elapsed from the beginning of the game loop to the end of the game loop. If everything is in one Thread then it’s easy, just take the time before and after and determine the sleep time and if it’s necessary to do extra updates.
If you are going to use a separate Thread for logic then you’re going to run into this:
If the logic Thread takes longer to execute than the Draw Thread then you’re never going to be drawing the state correctly:
This tables shows the total time elapsed and the loop nr for the logic and draw.
[tr][td]time[/td][td]logic[/td][td]draw[/td][/tr]
[tr][td]10[/td][td]1[/td][td]1[/td][/tr]
[tr][td]20[/td][td]1[/td][td]2[/td][/tr]
[tr][td]30[/td][td]2[/td][td]3[/td][/tr]
[tr][td]40[/td][td]3[/td][td]4[/td][/tr]
[tr][td]50[/td][td]3[/td][td]5[/td][/tr]
I’d say the time taken during the drawing routine would be roughly the same every loop, but the time needed for the logic can change more due to whatever is currently happening. So in the above table your drawing loop is going to be drawing along happily while the logic Thread is still trying to figure out what moves where. If the inverse was going to happen (ie. updates quicker than drawing) then you’re going to have updates not drawn to the screen. So in the worst case you’re either going to have updates skipped, or resources wasted due to excessive drawing. To ensure this doesn’t happen you’re going to have to synchronize the threads and that will probably be by having the one thread wait for the other to finish one iteration of the loop.
If you take a look at the single Thread method then that is exactly what is happening. So basically in the single Thread the drawing follows the logic so you don’t have to synchronize. Now if the loop was to take longer than the required time then you just add a few extra updates in the next loop iteration until you’re on time again. So in both cases you might have updates skipped, but there’s less to take care of in the single Thread method.
I have done a simple shooter base on the KGPJ book using his single Thread method and it works fine. You just have to take care to not place the game logic directly into the GPanel class.