useInput

useInput provides keyboard and pointer input for game logic. It reads from the InputManager which is automatically set up by Game.

tsx
import { useInput } from "@carverjs/core/hooks";

Quick Start #

tsx
import { useGameLoop, useInput } from "@carverjs/core/hooks";

function Player() {
  const { isPressed, pointer } = useInput();

  useGameLoop((delta) => {
    if (isPressed("KeyW")) moveForward(delta);
    if (isPressed("KeyS")) moveBackward(delta);
    if (pointer.isDown) shoot();
  });

  return <Actor type="primitive" shape="box" color="blue" />;
}

Return Value #

PropertyTypeDescription
isPressed(code)(string) => booleantrue while the key is held
isJustPressed(code)(string) => booleantrue only on the frame the key was first pressed
isJustReleased(code)(string) => booleantrue only on the frame the key was released
isAction(name)(string) => booleantrue if any key bound to the action is held
isActionJustPressed(name)(string) => booleantrue if any key bound to the action was just pressed
getAxis(neg, pos)(string, string) => numberReturns -1, 0, or 1
pointerPointerStateLive pointer state (position, isDown, justDown, justUp)

Options #

tsx
const input = useInput({
  actions: {
    jump: ["Space", "KeyW"],
    moveLeft: ["KeyA", "ArrowLeft"],
    moveRight: ["KeyD", "ArrowRight"],
  },
  enabled: true,
});
OptionTypeDefaultDescription
actionsRecord<string, string[]>{}Maps logical action names to key codes
keysstring[]Subscribe to specific keys only
enabledbooleantrueToggle this hook on/off

Action Mapping #

Instead of checking raw key codes, define actions:

tsx
const { isAction, isActionJustPressed } = useInput({
  actions: {
    jump: ["Space"],
    fire: ["KeyF", "MouseLeft"],
  },
});

useGameLoop(() => {
  if (isActionJustPressed("jump")) player.jump();
  if (isAction("fire")) player.fire();
});

Axis Input #

getAxis returns a value for two-key directional input:

tsx
const { getAxis } = useInput();

useGameLoop((delta) => {
  const moveX = getAxis("KeyA", "KeyD");     // -1, 0, or 1
  const moveY = getAxis("KeyS", "KeyW");     // -1, 0, or 1

  player.position.x += moveX * speed * delta;
  player.position.y += moveY * speed * delta;
});

Pointer State #

The pointer property is a live reference — always current when read inside useGameLoop:

tsx
const { pointer } = useInput();

useGameLoop(() => {
  if (pointer.justDown) {
    console.log("Clicked at", pointer.position.x, pointer.position.y);
  }
});
FieldTypeDescription
position{ x: number, y: number }Screen-space coordinates in pixels
isDownbooleanPrimary button is held
justDownbooleanButton was pressed this frame
justUpbooleanButton was released this frame

Key Codes #

Key codes follow the KeyboardEvent.code standard:

KeyCode
W"KeyW"
A"KeyA"
S"KeyS"
D"KeyD"
Space"Space"
Shift"ShiftLeft"
Arrow Up"ArrowUp"
Enter"Enter"
Escape"Escape"

Type Definitions #

See Types for UseInputOptions, UseInputReturn, ActionMap, KeyState, and PointerState.