Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GLFW switching boolean toggle

Tags:

c++

opengl

glfw

I am using GLFW for keyboard input but the processing happens too quick thus my boolean switch on a single press gets changed like 10 times, as input is processed every frame. All I need that for a single press of space bar it would switch the state. My current code is below:

if (glfwGetKey(window, GLFW_KEY_SPACE) == GLFW_PRESS)
{
    show = !show;
}

Is there a better way of doing this?

like image 269
user1031204 Avatar asked Mar 31 '26 16:03

user1031204


1 Answers

Yes. glfwGetKey is meant to be used for continuous key input. GLFW manual lists glfwSetKeyCallback as a better alternative if you want one-time notification about key press.

Thus, for your case it'd be something like this:

void key_callback(GLFWwindow* window, int key, int scancode, int action, int mods)
{
    if (key == GLFW_KEY_SPACE && action == GLFW_PRESS)
        show = !show;
}

If you don't want to use this method for whatever reason, you can always implement a similar thing yourself. You'll need a boolean value (or array of values) representing the key state. Then, in your input handling, you must only react on the change of the button state, like so:

bool spacePressed;

// in handling
bool spaceCurrentlyPressed = glfwGetKey(window, GLFW_KEY_SPACE) == GLFW_PRESS;

if (!spacePressed && spaceCurrentlyPressed) { // wasn't before, is now
    show = !show;
}
spacePressed = spaceCurrentlyPressed;
like image 108
Bartek Banachewicz Avatar answered Apr 02 '26 07:04

Bartek Banachewicz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!