Reputation: 45
I'm making games in Java. I'm using this game loop:
public void run() {
this.requestFocus();
double firstTime = 0;
double lastTime = System.nanoTime() / 1000000000.0;
double unprocessedTime = 0;
double passedTime = 0;
boolean render = false;
double frameTime = 0;
int frames = 0;
int fps = 0;
while (running) {
render = false;
firstTime = System.nanoTime() / 1000000000.0;
passedTime = firstTime - lastTime;
lastTime = firstTime;
unprocessedTime += passedTime;
frameTime += passedTime;
while (unprocessedTime >= UPDATE_CAP) {
unprocessedTime -= UPDATE_CAP;
render = true;
// TODO: update game
if (frameTime >= 1.0) {
fps = frames;
frameTime = 0;
frames = 0;
System.out.println("FPS: " + fps);
}
}
if (render) {
frames++;
tick();
render();
} else {
try {
Thread.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
stop();
}
I have a problem - FPS are dropping very low, even when there's only menu opened and pretty much nothing is happening.
FPS: 60
FPS: 61
FPS: 61
FPS: 61
FPS: 61
FPS: 48
FPS: 25
FPS: 8
FPS: 3
FPS: 4
FPS: 61
I have no idea why this is happening. If you want I can share more game code.
..................................
Upvotes: 0
Views: 172
Reputation: 45
I know what happened: I was creating a lot of Font objects every tick:
public void render(Graphics g) {
Font f1 = new Font("SansSherif", Font.BOLD, 20);
Font f2 = new Font("SansSherif", Font.BOLD, 50);
Font f3 = new Font("SansSherif", Font.BOLD, 135);
}
Now, I'm creating them only when game starts.
Upvotes: 2