Search code examples
javaeclipseinputkeyboardlwjgl

LWJGL 2.9 moving a quad around the screen using keyboard input


Hi so I have a simple task which is to move a quad around the screen using the arrow keys. I'm using the LWJGL to make this very simple "game." However I've come across a problem. The keyboard input works and all but there is a major problem, you can't hold down the arrow key. it only moves when you click the key and release it right away. holding down does nothing.

Here is my clock class which I just used for time in the game:

public class Clock {

    private static long lastFrame;

    public static long getTime(){
        return (Sys.getTime() * 1000) / Sys.getTimerResolution();
    }

    public static int getDelta(){
        long currentTime = getTime();
        int delta = (int) (currentTime - lastFrame);
        lastFrame = getTime();
        return delta;
    }

    public static void initLastFrame(){
        lastFrame = getTime();
    }

}

And this is the method I'm using for movement when using the keyboard:

public void move(){
    while(Keyboard.next()){
        if(Keyboard.getEventKeyState()){
            if(Keyboard.getEventKey() == Keyboard.KEY_RIGHT){
                this.x += this.speed * getDelta();
            }
            if(Keyboard.getEventKey() == Keyboard.KEY_UP){
                this.y -= this.speed * getDelta();
            }
            if(Keyboard.getEventKey() == Keyboard.KEY_DOWN){
                this.y += this.speed * getDelta();
            }
            else if(Keyboard.getEventKey() == Keyboard.KEY_LEFT){
                this.x -= this.speed * getDelta();
            }
        } 
    }
}

Solution

  • Keyboard.getEventKeyState()
    

    will return true if the key was pressed and false if the it was release. You can set flags to decide which direction you should move.

    if (Keyboard.getEventKey() == Keyboard.KEY_A) {
        if (Keyboard.getEventKeyState()) {
            movingLeft = true;
            System.out.println("A Key Pressed");
        }
        else {
            movingLeft = false;
            System.out.println("A Key Released");
        }
    }
    

    And moving left according to movingLeft.

    There is an other solution for exactly this problem is simply using

    Keyboard.isKeyDown(Keyboard.KEY_A) 
    

    Pretty self explaining, returns true if A is down, false if not.