Teng Long
Teng Long

Reputation: 455

GLFW getkey 'esc' and close window

I'm trying to get a key input of 'esc' and close the window. I found two ways to do this the first one is:

static void key_callback(GLFWwindow* window, int key, int scancode, int action, int mods){
    if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS)
        glfwSetWindowShouldClose(window, GL_TRUE);
}

glfwSetKeyCallback(window, key_callback);

while(!glfwWindowShouldClose(window)){
    render();
}

the other one is:

    glfwSetInputMode(window, GLFW_STICKY_KEYS, GL_TRUE);

    while( glfwGetKey(window, GLFW_KEY_ESCAPE ) != GLFW_PRESS &&
              glfwWindowShouldClose(window) == 0 ){
    render();
}

I want to know if these two ways works the same? If there is any circumstance these two works differently.

Upvotes: 0

Views: 8310

Answers (1)

vallentin
vallentin

Reputation: 26197

You can say that they work kinda the same, but trust the glfwSetKeyCallback callback.

When you call glfwPollEvents then it takes all pending events and calls each respective callback accordingly. The problem is that glfwGetKey only returns the last state for the specified key.

This becomes a problem if you (chronologically) have a flow of events like this:

*Press Escape*
*Release Escape*
glfwPollEvents() <- Calls the callback two times
glfwGetKey(window, GLFW_KEY_ESCAPE) <- returns GLFW_RELEASE

The key callback will bet called for both the press and release. However glfwGetKey will return GLFW_RELEASE since that's the last state for the escape key.

So are they gonna act the same? Possibly. Can you rely on that always being the case? No.

Upvotes: 2

Related Questions