Question

I am creating a side scrolling game and currently when I press an arrow key, the character moves, pauses then moves indefinitely until the key is released.

The pause comes from Windows configuration with Key Delay, so you don't accidentally type in duplicate key presses if you hold down the key too long.

I want to know if there is a way to get rid of this.

Here is my code for key presses:

public void keyReleased(KeyEvent ke){}

public void keyTyped(KeyEvent ke){}

public void keyPressed(KeyEvent ke){
    int code = ke.getKeyCode();

    if(code == KeyEvent.VK_UP){
        if(playerY > 0){
            playerY-=speed;
            repaint();
        }
    }

    else if(code == KeyEvent.VK_DOWN){
        if(playerY < 600){
            playerY+=speed;
            repaint();
        }
    }

    else if(code == KeyEvent.VK_RIGHT){
        if(playerX < 800){
            playerX+=speed;
            repaint();
        }
    }

    else if(code == KeyEvent.VK_LEFT){
        if(playerX > 0){
            playerX-=speed;
            System.out.println(playerX);
            repaint();
        }
    }
}
Was it helpful?

Solution

When the key is pressed, you should set some variable by which you determine movement. On KeyReleased you unset this variable.

The way how you handle this it to call the method, for example moveLeft(), and in loop you are checking this variable. On KeyReleased, when you redefine it, the loop ends.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top