So I've been playing around with moving objects using KeyListeners and active rendering via while(true) loop.
CANVAS.createBufferStrategy(3);
BufferStrategy buffer = CANVAS.getBufferStrategy();
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice gd = ge.getDefaultScreenDevice();
GraphicsConfiguration gc = gd.getDefaultConfiguration();
BufferedImage bi = gc.createCompatibleImage(WIDTH * SCALE, HEIGHT * SCALE);
Graphics graphics = null;
Graphics2D g2d = null;
while (true) {
try {
// clear back buffer...
graphics = buffer.getDrawGraphics();
g2d = bi.createGraphics();
g2d.setColor(Color.WHITE);
g2d.fillRect(0, 0, WIDTH * SCALE, HEIGHT * SCALE);
// Draw stuff here using Java's Graphics Object!!!
// blit the back buffer to the screen
graphics.drawImage(bi, 0, 0, null);
RENDER.tick(graphics);
bi.flush();
if (!buffer.contentsLost())
buffer.show();
// Let the OS have a little time...
Thread.yield();
} finally {
if (graphics != null)
graphics.dispose();
if (g2d != null)
g2d.dispose();
}
}
But there's a problem where whenever I click on the window, the loop freezes in that state.
- Sprite moves if I press up/down/left/right, and I don't click on window.
- Sprite doesn't move if I clicked on window, then try to press up/down/left/right.
I've also noticed that:
- Sprite continues to move in directed direction as if I've not released direction key, after I've clicked on the window.
I've also tried using just Graphics instead of Graphics2D but there didn't seem to be a difference. Really can't find the problem to this..