glfwGetKey
Asks whether a key is held down right now. Best for continuous actions such as walking with WASD.
Signature
int glfwGetKey(GLFWwindow* window, int key);
How it works
There are two ways to read the keyboard. Polling asks every frame "is W down?": perfect for movement, where the camera moves for as long as the key is held. Events (glfwSetKeyCallback) tell you once per press: better for toggles such as "P pauses", which would otherwise flip 60 times per second.
The answer is the state seen by the last glfwPollEvents, so call this after polling.
Parameters
The window that has the keyboard focus.
A key constant. Names follow the US layout POSITION: GLFW_KEY_W is the key where W sits on a US keyboard, even on AZERTY.
Common values
- GLFW_KEY_A … GLFW_KEY_Z, GLFW_KEY_0 … GLFW_KEY_9
- Letters and digits.
- GLFW_KEY_SPACE, GLFW_KEY_ESCAPE, GLFW_KEY_ENTER
- Space, Esc, Enter.
- GLFW_KEY_LEFT_SHIFT, GLFW_KEY_LEFT_CONTROL
- Modifiers as keys (e.g. Shift to run).
- GLFW_KEY_UP / DOWN / LEFT / RIGHT
- Arrow keys.
- GLFW_KEY_F1 … GLFW_KEY_F25
- Function keys.
Return value
GLFW_PRESS if the key is down, GLFW_RELEASE if it is up. Never GLFW_REPEAT.
Tips & pitfalls
Multiply movement by the frame time (deltaTime from
glfwGetTime), or the camera moves faster on faster computers.A press shorter than one frame can be missed. Turn on GLFW_STICKY_KEYS with
glfwSetInputMode, or use the key callback.
Errors
When the call is invalid it does nothing and sets an error, which glGetError returns:
- GLFW_NOT_INITIALIZED
- Called before glfwInit or after glfwTerminate.
- GLFW_INVALID_ENUM
- A hint, mode, key or button argument is not a valid GLFW constant.
Example
1float speed = 2.5f * deltaTime;
2if (glfwGetKey(window, GLFW_KEY_W) == GLFW_PRESS) camPos += speed * camFront;
3if (glfwGetKey(window, GLFW_KEY_S) == GLFW_PRESS) camPos -= speed * camFront;
4if (glfwGetKey(window, GLFW_KEY_A) == GLFW_PRESS) camPos -= speed * camRight;
5if (glfwGetKey(window, GLFW_KEY_D) == GLFW_PRESS) camPos += speed * camRight;