Input Handling

Input Interface

Reading the input state is a common operation in any game. As such, let's define the interface that will be comfortable to use to read input key states.

Technically, SFML already provides such functionalities through the sf::Keyboard namespace, but that API directly reads the keystates from the OS, even when the window is running in the background. As such, it requires input monitoring access, which on MacOS is a permission that has to be added to the application.

In this case, such low-level capabilities are not needed, so instead we'll make our own input wrapper that works by handling the input events that originate from the managed window object. By polling the events at the beginning of the window loop, the freshness of the state of the keyboard will only depend on the latency of the events sent to the window, which is usually negligible, and the go-to option for most libraries and engines.

engine/input.h
#pragma once

#include <SFML/Window/Keyboard.hpp>

namespace ng {

/// @brief Manages keyboard input, tracking key presses, holds, and releases.
class Input {
 public:
  /// @brief Checks if a specific key was pressed down (went from not pressed to pressed) in the current frame.
  /// @param key The SFML scancode of the key to check.
  /// @return True if the key was pressed down, false otherwise.
  [[nodiscard]] bool GetKeyDown(sf::Keyboard::Scancode key) const;

  /// @brief Checks if a specific key is currently being held down.
  /// @param key The SFML scancode of the key to check.
  /// @return True if the key is currently pressed, false otherwise.
  [[nodiscard]] bool GetKey(sf::Keyboard::Scancode key) const;

  /// @brief Checks if a specific key was released (went from pressed to not pressed) in the current frame.
  /// @param key The SFML scancode of the key to check.
  /// @return True if the key was released, false otherwise.
  [[nodiscard]] bool GetKeyUp(sf::Keyboard::Scancode key) const;
};

}  // namespace ng
  • GetKeyDown: "just pressed", "jump" action

  • GetKey: "pressing now", contiguous actions, such as "player movement"

  • GetKeyUp: "just released", "release bow arrow" action

Key State

Now that the interface is defined, we need to implement it.

Input Event Detection

Finally, the input events need to be handled to update the current state of the keys.

Last updated