Hey everyone, I have been programming my past games using the “traditional” method of just having the run method sleep for a certain amount of time and then repainting, however want to switch to the Active Rendering method.
I am having trouble finding articles, tutorials, etc. on this topic and am having trouble figuring out how to implement it. Looking at the source code for Metagun by notch I was able to implement his loop into my game, however do not understand certain parts.
Why does the code sleep for 500 seconds beforehand? If i take this piece of code out, I get a NullPointer error when trying to render the screen, not sure why this is happening.
But my main questions is what does the while(unprocessedTime > 0) loop does.
lastly, how would I implement an FPS counter in this type of loop?
public void run() {
requestFocus();
Image image = new BufferedImage(320, 240, BufferedImage.TYPE_INT_RGB);
setScreen(new TitleScreen(this));
long lastTime = System.nanoTime();
long unprocessedTime = 0;
[b] try {
Thread.sleep(500);
} catch (InterruptedException e1) {
e1.printStackTrace();
}[/b]
while (running) {
Graphics g = image.getGraphics();
long now = System.nanoTime();
unprocessedTime += now - lastTime;
lastTime = now;
int max = 10;
[b]while (unprocessedTime > 0) {
unprocessedTime -= 1000000000 / 60;
fps = unprocessedTime;
screen.update(input);
input.update();
if (max-- == 0) {
unprocessedTime = 0;
break;
}
}[/b]
screen.render(g);
g.dispose();
try {
started = true;
g = getGraphics();
g.drawImage(image, 0, 0, GAME_WIDTH * SCREEN_SCALE, GAME_HEIGHT * SCREEN_SCALE, 0, 0, GAME_WIDTH, GAME_HEIGHT, null);
g.dispose();
} catch (Throwable e) {
}
try {
Thread.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
Thanks guys, any resources, links or anything at all will help, I really want to learn what is happening rather then just get it working.