GLFW Keyboard Input

Wouldn’t it be nice to give our users the ability to interact with our game or application?

In a simple C++ console application, we might use getchar(), scanf(), cin or std::in to grab keyboard input. However, those input methods have some limitations that preclude their use in a game:

  • Can’t read arrow keys, modifiers (shift, control, etc.), numpad 5, Sys.Req, Escape, function keys… and a lot of others.
  • Blocking! If we call, say, scanf(), the application will halt until scanf() has received and processed input.
  • We would need a console window open – and in focus, potentially hiding our beautiful, painstakingly-crafted game window behind fixed-width gray text and a blinking cursor.

So, the C++ standard input handlers aren’t for us.

We could delve into assembly code and make calls to the HID driver for our keyboard, but then, two things are wrong:

  1. We’re writing assembly code.
  2. We’re now locked to a single platform.

What TO do?

Fortunately, GLFW makes cross-platform keyboard input easy. The simplest approach is to poll the keyboard each frame to determine if a key is down, using glfwGetKey().

For instance, we might want to use the ESC (escape) key to shut down our game:

[code language=”cpp”]
window : GLFWwindow* for our game window.
if (glfwGetKey(window,GLFW_KEY_ESCAPE) == GLFW_PRESS)

If you’d rather avoid polling for every key on every frame, you can let GLFW alert you when a key is pressed or released via a callback function. See glfwSetKeyCallback() and the GLFW documentation for details and examples.