InputManager

InputManager is a singleton that captures keyboard, pointer, and touch events from the DOM and makes them available to game logic on a per-frame basis.

It is mounted automatically by Game — you do not need to set it up manually.

tsx
import { getInputManager } from "@carverjs/core/systems";

How It Works #

  1. DOM events (keydown, keyup, pointerdown, pointerup, pointermove, touch events) are captured asynchronously and queued.

  2. Once per frame (at priority -50, before all game logic), flush() processes the queued events and updates key/pointer state.

  3. Game logic reads the current state via getKey() and getPointer().

This ensures consistent input state within a single frame — no matter when a DOM event fires, the state only changes at the start of the next frame.


Frame-Based Input States #

Each key tracks three states per frame:

StateMeaning
pressedKey is currently held down
justPressedKey was first pressed this frame
justReleasedKey was released this frame

The pointer tracks equivalent states:

StateMeaning
isDownPrimary button is held
justDownButton was pressed this frame
justUpButton was released this frame
positionScreen-space { x, y } in pixels

API #

getInputManager() #

Returns the singleton InputManager instance. Creates one if it doesn't exist.

destroyInputManager() #

Detaches all DOM listeners and destroys the singleton. Called automatically when Game unmounts.

manager.getKey(code: string): KeyState #

Returns the state of a key by its KeyboardEvent.code (e.g., "KeyW", "Space", "ArrowUp").

manager.getPointer(): PointerState #

Returns a live reference to the pointer state. Always up-to-date when read inside useGameLoop.


Usage #

Most game code should use the useInput hook instead of accessing InputManager directly. The hook provides a cleaner API with action mapping and axis helpers.

Direct access is useful for systems-level code:

tsx
import { getInputManager } from "@carverjs/core/systems";
import { useGameLoop } from "@carverjs/core/hooks";

function MySystem() {
  useGameLoop(() => {
    const mgr = getInputManager();
    if (mgr.getKey("Space").justPressed) {
      // fire
    }
  });
  return null;
}

Type Definitions #

See Types for KeyState and PointerState.