Search code examples
openglwindowlwjglglfw

GLFW Keyboard Input Registers As Multiple Clicks


In my current LWJGL application I am using the GLFW window input handler which I have set up a class to handle called Keyboard.java which extends GLFWKeyCallback. I have correctly set up my keyboard input class but when I click on a key if i do not click if fast enough (very quickly) then it registers as multiple clicks. I have presented some documentation below:

Keyboard Class

public class Keyboard extends GLFWKeyCallback {

    //Variables
    public static boolean keys[] = new boolean[65536];

    @Override
    public void invoke(long window, int key, int scancode, int action, int mods) {

        keys[key] = action == GLFW_PRESS;

    }

}

Implementation

public static void handleInput() {
    if (Keyboard.keys[GLFW_KEY_SPACE]) {
        System.out.println("Space");
        glfwPollEvents();
    }
}

The above method is implemented in the main game loop and is called once a frame.

Result

Initialised LWJGL Version: 3.1.2 build 29

Space

Space

Space

Space

The above: "Space" should be outputted every time that I click space but when I click it relatively fast, Then i get the above result of many "spaces".

Conclusion: Is it possible for a click of space to be registered only once no matter how long you hold it. Thanks


Solution

  • In your handleInput() function, you are testing to see if Keyboard.keys[GLFW_KEY_SPACE] is true, and if it is, you execute the statement. The problem is that this test only becomes false when you stop hitting space, which could take seconds to happen.

    My suggestion: once you tested for Keyboard.keys[GLFW_KEY_SPACE], make it false.

    public static void handleInput() {
        if (Keyboard.keys[GLFW_KEY_SPACE]) {
            Keyboard.keys[GLFW_KEY_SPACE] = false;
            System.out.println("Space");
            glfwPollEvents();
        }
    }