I try to write my own game loop. But the cpu usage is too high. It's about 25%. My problem could be that there is no Thread.sleep. But I don't want to use it beacuse it should be not very accurate. Also calculating the next frame could need 10 ms.
My code is doing this:
1: repaint the window ('fenster' is window in german)
2: read out the milliseconds
3: set up the next frame
I wanna have 50 fps. So the program need to wait 1000/50 = 20 ms every frame.
4: Calculate the difference of the time for and after setting up the next frame
// GameSchleife
while (true) {
// First repaint
fenster.repaint();
// Before calculating the next frame, capture the time
long a = System.currentTimeMillis();
long b = a;
// Calculate the next frame
fenster.Update();
// Wait for 20 ms (50 frames in a second)
for (int time = 0; time < 20;) {
// Wait for at least 1 ms
while (a == b) {
a = System.currentTimeMillis();
}
// Difference from a and b
time = time + ((int) (a - b));
//
a = System.currentTimeMillis();
b = a;
}
}