Is this an efficient method for getting a single click as input?

Started by FoldableClock, July 29, 2016, 15:45:29

Previous topic - Next topic

FoldableClock

I noticed that simply checking if a key == GLFW_PRESS returns true when the key is held down, and even a single click returns true many times. In an attempt to fix this I created a basic input class with two methods that looks like this:

public void leftMousePressed(long window, Map map) {
        if (glfwGetMouseButton(window, GLFW_MOUSE_BUTTON_LEFT) == GLFW_PRESS && leftCount < 1) {
            leftCount++;

            map.selectTile(map.getMouseRow(window), map.getMouseCol(window));
        }

        if (glfwGetMouseButton(window, GLFW_MOUSE_BUTTON_LEFT) == GLFW_RELEASE) {
            leftCount = 0;
        }
    }


With another method like this for the right mouse button.

These methods get called in the update method of my game class and then checked every pass through of the game loop. This way of checking for a single press of a key/mouse button definitely works, my question to you all is: is it efficient? Is there a noticeably better way that I could go about doing this?

spasi

Yes, you should be using callbacks, glfwSetMouseButtonCallback in this case. See the Events sample for ideas.

FoldableClock

Ok, so doing some experimenting by setting mouseButtonCallback, and I still run into the problem that I can't check for a single click.

public static boolean[] buttons = new boolean[2];

    @Override
    public void invoke(long window, int button, int action, int mods) {
        buttons[button] = action == GLFW_PRESS;
    }


This still sets the button to true if the mouse is held down, but I'm looking for it to only be true when the button is clicked once. I feel like I'm just overthinking this, any help would be appreciated.  ;D

Cornix

You usually do this with double buffering. You keep 2 variables, the "now" value and the "old" value. In each tick of the update loop you write the "now" value into the "old" value. Then you read the new "now" value from the mouse button callback.
With both the "old" and "now" values you can find out whether the mouse was just pressed (old == false, now == true), the mouse was just released (old == true, now == false) or whether it has been continously pressed (old == now == true).

FoldableClock