当前位置: 动力学知识库 > 问答 > 编程问答 >

Unprocessed time in java game loop

问题描述:

I was looking at notch's game loop and i can't understand what is the meaning of unprocessedTime variable.

long now = System.nanoTime();

unprocessedTime += now - lastTime;

lastTime = now;

I would be really grateful if someone could explain me the difference between the two variables.Thanks

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;

try {

Thread.sleep(500);

} catch (InterruptedException e1) {

e1.printStackTrace();

}

while (running) {

Graphics g = image.getGraphics();

long now = System.nanoTime();

unprocessedTime += now - lastTime;

lastTime = now;

int max = 10;

while (unprocessedTime > 0) {

unprocessedTime -= 1000000000 / 60;

fps = unprocessedTime;

screen.update(input);

input.update();

if (max-- == 0) {

unprocessedTime = 0;

break;

}

}

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();

}

}

}

网友答案:

This is accumnulating the lapsed time in nanoseconds between the last time the event was triggered...

According to Java Doc (if you need to know about nanoTime) System.nanoTime();

Returns the current value of the most precise available system timer, in nanoseconds. This method can only be used to measure elapsed time and is not related to any other notion of system or wall-clock time. The value returned represents nanoseconds since some fixed but arbitrary time (perhaps in the future, so values may be negative). This method provides nanosecond precision, but not necessarily nanosecond accuracy. No guarantees are made about how frequently values change. Differences in successive calls that span greater than approximately 292 years (263 nanoseconds) will not accurately compute elapsed time due to numerical overflow.

分享给朋友:
您可能感兴趣的文章:
随机阅读: