Take the 2-minute tour ×
Game Development Stack Exchange is a question and answer site for professional and independent game developers. It's 100% free, no registration required.

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..

share|improve this question
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Browse other questions tagged or ask your own question.