Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.5k views
in Technique[技术] by (71.8m points)

glfw - How to detect a key press only once without glfwSetKeyCallback()

I have a bit of a problem.

Im trying to make a small game and to sum it up my GLFWwindow* window is a Game.h class variable.

If I understand it correctly (or at least thats how it works for me) in order to use different window callback functions such as:

  • glfwSetFramebufferSizeCallback()
  • glfwSetKeyCallback()

I need to pass static functions i.e static void key_callback(GLFWwindow* window, int, int, int, int) as their parameter.

So this function looks somewhat like this:

void Game::key_callback(GLFWwindow* window, int key, int scancode, int action, int mods) //this is declared as static
{
    if (key == GLFW_KEY_F11 && action == GLFW_PRESS) {
        changeScreen();
    }
    if (key == GLFW_KEY_M && action == GLFW_PRESS) {
        changeMouse();
    }
}

and changeScreen() translates into:

void Game::changeScreen()
{
    screenState = !screenState;
    if (screenState) {
        glfwSetWindowMonitor(window, 0, 200, 200, 600, 600, GLFW_DONT_CARE);
    }
    else {
        glfwSetWindowMonitor(window, glfwGetPrimaryMonitor(), 0, 0, 2560, 1440, GLFW_DONT_CARE);
    }
}

The problem is that window as well as changeScreen() and its variables are not static and thus I cant use them.

Therefore the easiest way to solve it would be how I did with all of my other keys, for example:

if (glfwGetKey(this->window, GLFW_KEY_ESCAPE) == GLFW_PRESS)
    {
        glfwSetWindowShouldClose(this->window, GLFW_TRUE);
    }

So I need to somehow be able to detect the key press only once using this method. I am open to any other solutions to my problem. But If there was some dumb way (this really doesnt need to work extremely reliably) I would like to use it since at this stage reworking the project and making the window global or at least not a member of class would give me a headache.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

This is not a solution but for now calling:

glfwWaitEventsTimeout(float time); //my time is set for 0.7 and its quite fluid

makes the button press register just once if I press the button and release swiftly.

if (glfwGetKey(this->window, GLFW_KEY_F11) == GLFW_PRESS) {
    glfwWaitEventsTimeout(0.7);
    changeScreen();
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...