inputHandlers.js

Input Handlers

Two input handler classes — simple left/right/space for action games, four-dir queue for RPG movement.

Input Handlers

Two classes covering the two most common input patterns in DN games.

Include

<script src="/js/dn/inputHandlers.js"></script>

InputHandler

Simple stateful key tracker with built-in mouse/touch support. Best for paddle games, platformers, menus, and anything that needs “is this key held right now?”

Keys supported: Arrow keys + WASD + Space

const input = new InputHandler();

// In update:
if (input.leftPressed)  { /* move left */  }
if (input.rightPressed) { /* move right */ }
if (input.upPressed)    { /* jump */       }
if (input.spacePressed) { /* fire */       }

// Mouse X position (set after registerMouseMove)
if (input.mouseX !== null) {
  paddle.x = input.mouseX;
}

Mouse & Touch Support

Call registerMouseMove(canvas) once after creating the input handler. This sets input.mouseX and input.mouseY in canvas-local coordinates on both mousemove and touchmove events. A tap also triggers a brief spacePressed = true pulse.

const input = new InputHandler();
input.registerMouseMove(canvas);  // canvas = your HTMLCanvasElement

Used In

LoopShoots — paddle control (mouse priority over keyboard)


FourDirInputHandler

Direction history queue for tile-based movement. Tracks key press order so “most recently held” direction always wins. Good for RPGs and grid puzzles.

const input = new FourDirInputHandler();
input.activateArrows();     // register arrow keys
input.activateWASD();       // register WASD (both can be active)
input.setInteractKey('e');  // optional interact/confirm key

// In update (once per fixed step):
const dir = input.getMostRecent();
// dir = 'ArrowUp' | 'ArrowDown' | 'ArrowLeft' | 'ArrowRight'
//       'w' | 'a' | 's' | 'd'
//       '' (nothing held)

if (input.interactPressed) { /* open chest, talk to NPC, etc. */ }

Method Reference

MethodDescription
activateArrows()Register arrow keys (idempotent)
activateWASD()Register WASD keys (idempotent)
setInteractKey(key)Set the interact/confirm key string
getMostRecent()Returns the most recently pressed held direction key, or ''

Used In

flintJs RPG — player tile movement and NPC interaction


Choosing the Right Handler

ScenarioUse
Paddle game, shooter, platformerInputHandler
Tile-based RPG movementFourDirInputHandler
Mouse-only gameInputHandler + registerMouseMove()

Source

public/js/dn/inputHandlers.js