Skip to content
Tutorials Center
My learning

Topics

Lesson 14 of 36 ยท Input and Physics

Phaser Keyboard Input: Cursors, WASD, Key Events

Handle the keyboard in Phaser: cursor keys, WASD, addKey and addKeys, isDown, JustDown, key events, combos, cooldown shooting and focus tips, with live examples.

Now the game starts listening. Phaser's keyboard plugin turns raw browser key events into easy objects and events that you read in update or react to with listeners. This lesson covers the two styles, polling and events, and the details that trip people up: held versus just-pressed, diagonal speed, repeat, focus and browser shortcuts.

Click the game first. The preview is a separate frame; the keyboard goes to it only after you click inside the game once. In a normal page the game has keyboard focus as soon as the page does.

Two styles: polling and events

  • Polling means asking every frame, "is this key down right now?". It suits continuous actions: walking, steering, holding to charge.
  • Events mean being told when something happens: "the jump key was pressed". It suits one-time actions: jump, pause, open the menu.

Use polling for movement and events (or JustDown) for actions.

Cursor keys and WASD

JavaScript
create() {
  this.cursors = this.input.keyboard.createCursorKeys();   // up, down, left, right, space, shift
  this.wasd = this.input.keyboard.addKeys('W,A,S,D');       // or an object: { up: 'W', left: 'A' }
}

update() {
  if (this.cursors.left.isDown) { /* moving left */ }
}

createCursorKeys() returns an object with up, down, left, right, space and shift. addKeys('W,A,S,D') returns an object whose properties are named after the keys you listed. With a custom mapping ({ up: 'W', down: 'S', left: 'A', right: 'D' }) you get friendlier names. Phaser's key codes are in Phaser.Input.Keyboard.KeyCodes, so you can also write this.input.keyboard.addKey(Phaser.Input.Keyboard.KeyCodes.SPACE) or just addKey('SPACE').

A Key object has useful properties:

Property Meaning
isDown, isUp current state
duration how long it has been held (ms)
timeDown, timeUp timestamps
repeats auto-repeat count while held
enabled set to false to ignore the key

Held versus just pressed

isDown is true on every frame while the key is held. That is wrong for "jump once". If you jump whenever isDown, holding the key repeats the jump the moment you land. Use Phaser.Input.Keyboard.JustDown(key), which returns true only on the first frame after the press (and false afterwards, until released):

JavaScript
if (Phaser.Input.Keyboard.JustDown(this.spaceKey)) {
  this.jump();               // once per press
}

Careful: JustDown consumes the press. Calling it twice for the same key in one frame gives true then false, so call it once and store the result.

Events

JavaScript
this.input.keyboard.on('keydown-SPACE', () => this.shoot());   // pressing SPACE
this.input.keyboard.on('keyup-SPACE', () => this.stopCharging());
this.input.keyboard.on('keydown', (event) => console.log(event.key, event.code));  // any key

The event names are keydown- followed by the key name in capitals: keydown-A, keydown-ENTER, keydown-ESC, keydown-LEFT. Events fire once per physical press and then repeat while the key is held if the browser auto-repeats; check event.repeat to ignore repeats.

For combos (Ctrl + S, or a cheat code) use this.input.keyboard.createCombo('IDDQD', { resetOnMatch: true }) and listen for the keycombomatch event.

Moving at a steady speed in every direction

A beginner mistake: add the x speed and the y speed separately. Moving diagonally then goes at 1.41 times the speed (the diagonal of a square). Fix by building a direction vector and normalizing it to length 1:

JavaScript
const dir = new Phaser.Math.Vector2(0, 0);
if (left.isDown)  dir.x -= 1;
if (right.isDown) dir.x += 1;
if (up.isDown)    dir.y -= 1;
if (down.isDown)  dir.y += 1;
dir.normalize();                                   // length 1 (or 0 if no keys)
this.ship.x += dir.x * speed * delta / 1000;
this.ship.y += dir.y * speed * delta / 1000;

With Arcade Physics you use body.setVelocity(dir.x * speed, dir.y * speed) instead, and body.velocity.normalize().scale(speed) also works.

Move with arrows or WASD, shoot with space

Notice three techniques in one scene: normalized direction for even diagonal speed, Clamp to keep the ship on screen, and a cooldown (nextShot) so holding space fires a steady stream rather than one bullet per frame.

Preventing the browser from reacting

The arrow keys and space bar scroll a web page. Phaser's createCursorKeys and addKey automatically capture those keys (preventDefault) so the page does not scroll while you play. If you only use events without keys, capture manually: this.input.keyboard.addCapture('SPACE,UP,DOWN'). Release with removeCapture.

Capturing also means those keys stop working for the rest of the page. If your game sits inside a page with text inputs, remember to disable the keyboard plugin while a field has focus: this.input.keyboard.enabled = false.

Typing text

For text fields (name entry, chat), listen to keydown and read event.key:

JavaScript
this.input.keyboard.on('keydown', (e) => {
  if (e.key === 'Backspace') this.name = this.name.slice(0, -1);
  else if (e.key.length === 1 && this.name.length < 10) this.name += e.key;
  this.nameText.setText(this.name);
});

event.key.length === 1 filters out special names such as Shift and ArrowLeft. For real text entry on phones, use an HTML input through the DOM element feature of the game config instead, because virtual keyboards do not fire game key events reliably.

Rebinding keys

Do not scatter 'SPACE' everywhere. Put key names in one config object and let the player change them later:

JavaScript
const controls = { jump: 'SPACE', left: 'A', right: 'D' };
this.keys = this.input.keyboard.addKeys(controls);

Common mistakes

  • Using isDown for jumping. It repeats every frame; use JustDown or the keydown- event.
  • Calling JustDown twice per frame for the same key; only the first call is true.
  • Diagonals twice as fast. Normalize the direction.
  • Keys do nothing in the preview. The frame must be focused: click the game once.
  • Creating the keys in update. Create them once in create.
  • Forgetting to turn off capture when a form field should receive spaces and arrows.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. You want a jump that triggers once per key press, not continuously while held. What do you use?

    JustDown is true only on the first frame after the press. isDown stays true for as long as the key is held.
  2. 2. What does createCursorKeys() return?

    It is a shortcut for the arrow keys plus space and shift.
  3. 3. Why does moving diagonally with separate x and y speeds feel too fast?

    Combining a full x and full y step moves along the diagonal of a square. Normalize the direction vector to fix it.
  4. 4. What is the event name for pressing the space bar?

    Keyboard events are named keydown-KEY and keyup-KEY, with the key name in capitals.
  5. 5. How do you stop a held space bar from firing a bullet on every frame?

    Compare the current time with nextShot and set nextShot to time + the delay each time you fire.

Summary

  • Poll keys with isDown in update for continuous actions; use JustDown or keydown-KEY events for one-time actions.
  • createCursorKeys and addKeys (arrows, WASD, custom maps) are created once in create.
  • Normalize direction vectors so diagonals are not faster, and use cooldowns for repeating actions like shooting.
  • Phaser captures the keys it uses so the page does not scroll; disable the plugin when a form needs the keyboard.
  • Keep key names in one place to make rebinding easy.

Next: Pointer, Mouse and Touch Input