@Override
public void run() {
while (running) {
currentState.update();
prepareGameImage();
// next line draws image(frame) to the screen
currentState.render(gameImage.getGraphics());
repaint();
}
// End game immediately when running becomes false.
System.exit(0);
}
private void prepareGameImage() {
if (gameImage == null) {
gameImage = createImage(gameWidth, gameHeight);
}
Graphics g = gameImage.getGraphics();
g.clearRect(0, 0, gameWidth, gameHeight);
}
this is a snippet of game loop. a little explanation from the book about how it works. In prepareGameImage() we prepare an off-screen image by creating and initializing the gameImage variable with a width of gameWidth and a height of gameHeight. (i dont get how this works --->) Next, on every frame, we clear this image using a rectangle of equal size to clear all images that have been drawn to the screen in the previous frame. This ensures that images from the previous frame do not bleed into the current frame. Every frame starts anew.
what i dont understand is last 2 lines of the snippet. value of gameImage.getGraphics(); gets stored inside of Graphics variableg. method g.clearRect(0, 0, gameWidth, gameHeight); should only affect variable g and should not affect value generated by gameImage.getGraphics();
could you explain how does the last 2 lines of code do the task - "images from the previous frame do not bleed into the current frame" :( :(
thanks