Please enable JavaScript to use CodeHS

Games & Animations with Three.js

Keyboard and Mouse Input in Three.js

Until now your scenes have run on their own. In this part you grab the controls: read the keyboard the way real games do, drive a cube around a grid with WASD, and tilt the camera with the mouse. This is the moment a scene turns into a game.

Part 10 of 12 ~15 min JavaScript
Part 10 of 12

What you'll learn

  • How a game reads the keyboard: the browser's keydown and keyup events, a key-state object that remembers which keys are held, and why the player moves in the animation loop, never inside the event handler.
  • How to turn held keys into a direction vector, normalize() it so diagonals are not faster, move by speed * dt, and turn the player to face where it is going.
  • How to capture keys politely: only when the stage is focused, only stopping the arrow keys from scrolling, and clearing everything on blur so no key gets stuck.
  • How to read the mouse or a finger with pointer events, convert the position to the -1..1 coordinates the rest of the series uses, and add on-screen buttons so the same game works on a phone.

The Big Idea

Remember what is held, then ask every frame

Here is a surprise: three.js has no input system. Nothing in THREE knows what a keyboard is. That is fine, because the browser already tells you everything: it fires a keydown event when a key goes down, a keyup when it comes back up, and pointermove whenever the mouse or a finger moves. Your job is to listen to those events and feed what they say into the animation loop you built in Part 7. Input in, motion out.

The tempting first attempt is to move the player right inside the event: keydown fires, so nudge player.position.z a little. It half works and feels terrible. When you hold a key, the browser does not fire keydown every frame. It fires once, waits about half a second, then repeats at whatever rate your operating system chose. So the player lurches forward, freezes, then stutters along at a speed you do not control. Hold two keys and the second one usually cancels the repeats of the first, so there is no diagonal movement at all.

The fix is the one idea on this page. Do not move anything in the event handler. Instead, keep a plain object, keys, that remembers the state of every key: on keydown write keys[e.code] = true, on keyup write false. That is the whole handler. Then, inside animate, ask a question every frame: "is W held right now?" If it is, move by speed * dt. Now the player moves the same distance per second on every computer, two keys work at once, and the events only have one small job to do.

Think of a light switch versus a doorbell. A doorbell is an event: it rings once when pressed, and holding it down does not ring it faster. A light switch is state: flip it and it stays flipped, and anyone who walks in later can see whether it is on. The browser hands you doorbells. A game needs switches, and keys is where you keep them.

Simple definition: a key-state object is a plain JavaScript object whose keys are key names and whose values are true (held) or false (not held). Event handlers write to it; the animation loop reads from it. The loop never waits for an event, and the events never move the player.


How It Works

Keys, the loop, the mouse

We keep the setup from Part 1 and the delta-time loop from Part 7 exactly as they were. The new code comes in three pieces: listen to the keyboard and remember what is held, turn what is held into movement each frame, and read the pointer. A fourth, short piece makes it all work on a phone.

1. The key-state object and its handlers

Every key event carries two names for the key, and you must pick the right one. e.key is the character the key produced: 'w', but 'W' with Shift or Caps Lock, and something else entirely on a French or German keyboard. e.code is the physical key: 'KeyW' no matter what Shift is doing or which language the keyboard speaks. Games want the physical key, so we use e.code everywhere. The names you will use most are 'KeyW', 'KeyA', 'KeyS', 'KeyD', 'ArrowUp' and friends, and 'Space'.

Where you listen matters too. Listening on window would grab every keystroke on the page, including the ones a reader needs to scroll the article or fill in the quiz. So the stage gets tabindex="0", which lets a <div> take focus when clicked, and we listen on that element. Key events only reach it while it is focused, so the rest of the page is untouched. Inside the handler, e.preventDefault() stops the arrow keys and Space from doing their normal job of scrolling, but we call it only for our game keys, so Tab, F5, and Ctrl+R keep working.

input.js
// The stage is the <div tabindex="0"> the canvas lives in: click it and it takes focus.
const stage = document.getElementById('main-stage');

const keys = {};    // the key-state object: keys['KeyW'] is true while W is held

const GAME_KEYS = ['KeyW', 'KeyA', 'KeyS', 'KeyD', 'ArrowUp', 'ArrowLeft', 'ArrowDown', 'ArrowRight', 'Space'];

stage.addEventListener('keydown', (e) => {
  if (!GAME_KEYS.includes(e.code)) return;   // not ours: let Tab, F5, Ctrl+R... through
  e.preventDefault();                        // arrows and Space must not scroll the page
  keys[e.code] = true;                       // e.code, not e.key: the physical key
});

stage.addEventListener('keyup', (e) => {
  keys[e.code] = false;                      // ...and now it's up
});

stage.addEventListener('blur', () => {
  for (const code in keys) keys[code] = false;   // clicked away or alt-tabbed: nothing is held anymore
});

Notice how little the handlers do: three assignments and a guard. The repeating keydown events a held key fires just write true again, which is harmless. The blur handler is the one people forget. If you hold W and click somewhere else, the keyup goes to whatever you clicked, not to the stage, so without it keys.KeyW stays true forever and the player runs away on its own.

2. The loop: from held keys to movement

Now the loop reads the switches. First, combine the two layouts: "up" means W or the up arrow, and so on, so both kinds of player are happy. Then build a direction vector from what is held. Along x, right counts +1 and left counts -1, so (right ? 1 : 0) - (left ? 1 : 0) gives 1, -1, or 0 if both or neither are held. Along z, remember from Part 2 that z points toward the camera, so "forward" into the screen is -1: (down ? 1 : 0) - (up ? 1 : 0). If the vector is all zeros, nothing is held, and the player stands still.

Here is the trap. W alone gives the direction (0, 0, -1), which is 1 unit long. W and D together give (1, 0, -1), and by the Pythagorean theorem that arrow is √2 ≈ 1.41 units long: one step right and one step forward is a longer stride than either alone. Multiply by the same speed and the diagonal player travels 41% faster, a bug shipped in more than one famous game. dir.normalize() fixes it by shrinking (or stretching) the vector to exactly length 1 while keeping its direction. Picture the four straight arrows and the four diagonal arrows all touching the same circle: that circle is what normalize draws.

With a unit-length direction, moving is one line: player.position.addScaledVector(dir, speed * dt) adds dir multiplied by speed * dt to the position, which is Part 7's rule (units per second times seconds this frame) in vector form. Facing is one more: Math.atan2(dir.x, dir.z) is the angle around y that points the player's front (its local +z, where our little nose sits) along dir, so the player turns to face where it is going. Last, a clamp keeps it inside the arena; there is no collision yet, that is Part 15.

move.js
const speed = 4;                        // units per SECOND (Part 7), not per frame
const ARENA = 4.5;                      // half the width of the grid
const dir = new THREE.Vector3();        // made once, reused every frame

function movePlayer(dt) {
  const up    = keys.KeyW || keys.ArrowUp;      // WASD and arrows both work
  const down  = keys.KeyS || keys.ArrowDown;
  const left  = keys.KeyA || keys.ArrowLeft;
  const right = keys.KeyD || keys.ArrowRight;

  dir.set((right ? 1 : 0) - (left ? 1 : 0), 0, (down ? 1 : 0) - (up ? 1 : 0));
  if (dir.lengthSq() === 0) return;             // nothing held: stand still

  dir.normalize();                                // diagonal is 1 long, not 1.41
  player.position.addScaledVector(dir, speed * dt);   // position += dir * speed * dt
  player.rotation.y = Math.atan2(dir.x, dir.z);   // turn to face where we're going

  player.position.x = THREE.MathUtils.clamp(player.position.x, -ARENA, ARENA);   // stay in the arena
  player.position.z = THREE.MathUtils.clamp(player.position.z, -ARENA, ARENA);
}

function animate() {
  const dt = Math.min(clock.getDelta(), 0.1);
  movePlayer(dt);                                  // read the switches, move
  renderer.render(scene, camera);
}
renderer.setAnimationLoop(animate);

This is the exact loop the "Try it" stage runs; every toggle down there switches one of these lines on or off. lengthSq() is the squared length, which is cheaper than length() and just as good for asking "is it zero?". THREE.MathUtils.clamp(value, min, max) is a tiny helper that pins a number between two limits.

3. The pointer: mouse and finger in one API

For the mouse we use pointer events, which is the modern name for "mouse and touch and pen, all through one set of events." pointermove fires as the pointer moves; pointerdown and pointerup are the press and release. The event gives e.clientX and e.clientY, the position in pixels from the top-left corner of the browser window. Pixels are not useful to a 3D scene, so we convert.

The conversion is worth memorizing, because Part 16 uses exactly the same numbers to click on 3D objects. Ask the canvas where it is with getBoundingClientRect(), subtract its left and top edges so the position is relative to the canvas, divide by its width and height to get 0..1, then stretch that to -1..1. One catch: on the screen y grows downward, but in three.js y is up, so we flip the sign for y. The result is a point where (0, 0) is the center of the canvas, (-1, 1) is the top-left corner, and (1, -1) is the bottom-right, whatever size the canvas happens to be. Here we use it for a small look-around: the camera slides a little in the direction of the mouse, then aims back at the player with lookAt, eased with the lerp trick from Part 9.

keydown / keyup

writes keys[e.code]

Fires once per press and once per release (plus repeats while held). Never move here: flip a switch in keys and let the loop do the work.

pointermove

writes mouse.x, mouse.y

Fires whenever the mouse or a finger moves over the stage. Convert clientX/Y to -1..1 and store it; the loop reads it like any other switch.

pointerdown

the "action" button

A click or a tap. Today it just focuses the stage; in Part 16 it fires a ray to pick an object, and in Part 18 it is the jump button.

4. Touch: same switches, different buttons

Phones do not have W, A, S, or D. But look at what the loop actually reads: it never sees the keyboard, only keys. So an on-screen button that sets keys.KeyW = true on pointerdown and false on pointerup is, as far as the game knows, the W key. Not a single line of movePlayer changes. That separation, input sources on one side and the game loop on the other, is why the key-state object is worth the extra few lines: a gamepad, a network message, or a scripted demo (that is what drives the hero cube above) can all press the same switches. We also handle pointercancel and pointerleave, which fire when a finger slides off the button or the browser interrupts the touch, so the button cannot get stuck down.

pointer.js
// --- mouse position as -1..1, the same numbers Part 16 uses for raycasting ---
const mouse = new THREE.Vector2();          // (0, 0) is the center of the canvas

stage.addEventListener('pointermove', (e) => {
  const r = renderer.domElement.getBoundingClientRect();
  mouse.x =  ((e.clientX - r.left) / r.width)  * 2 - 1;   // left edge -1, right edge +1
  mouse.y = -((e.clientY - r.top)  / r.height) * 2 + 1;   // top edge +1, bottom -1 (y flips!)
});
stage.addEventListener('pointerleave', () => mouse.set(0, 0));   // pointer gone: settle back to center
stage.addEventListener('pointerdown', () => stage.focus());     // Part 16: shoot. Part 18: jump.

// --- a small look-around: slide the camera toward the mouse, keep aiming at the player ---
const camHome = new THREE.Vector3(0, 7, 10);
const camGoal = new THREE.Vector3();

function tiltCamera(dt) {
  camGoal.set(camHome.x + mouse.x * 1.5, camHome.y + mouse.y * 1.0, camHome.z);
  camera.position.lerp(camGoal, 1 - Math.pow(0.001, dt));   // the easing from Part 9
  camera.lookAt(player.position);
}

// --- touch: an on-screen button IS the W key, as far as the loop can tell ---
const upButton = document.getElementById('pad-up');
upButton.addEventListener('pointerdown',   () => { keys.KeyW = true; });
upButton.addEventListener('pointerup',     () => { keys.KeyW = false; });
upButton.addEventListener('pointercancel', () => { keys.KeyW = false; });
upButton.addEventListener('pointerleave',  () => { keys.KeyW = false; });
// ...and the same four lines for pad-left (KeyA), pad-down (KeyS), pad-right (KeyD)

tiltCamera(dt) runs in animate right after movePlayer(dt). Give the D-pad touch-action: none in CSS so a finger on a button does not also scroll the page. In the demo the four buttons are wired in a small loop instead of copy-pasting; the idea is identical.


Try It

Drive the cube

Click the stage (or tap it, or Tab to it) to give it the keyboard, then drive with W A S D or the arrow keys. The lilac cube's nose shows which way it is facing. The scattered blocks are just scenery for now: you will drive straight through them until Part 15 adds collision. Move the mouse over the stage and the camera leans a little toward it. On a phone, use the D-pad under the stage. The key chips light up while a key is held, whichever way you press it, and the live code under the controls shows the keys object flipping in real time.

Loading 3D preview…

held: — · speed 4.0 · 0.00 u/s

While the stage has the lilac focus ring, the arrow keys drive the cube instead of scrolling. Click anywhere else, or press Tab, and the page gets its keys back.

Touch D-pad

move.js

4.0
Measured speed how far the cube actually moved this frame, divided by dt
0.00 u/s
Lines in the loop each button switches one line of move.js or pointer.js on or off
Live code: what the keys object holds and what the loop does with it
keys['KeyW'] = false;  keys['KeyA'] = false;  keys['KeyS'] = false;  keys['KeyD'] = false;
// inside animate(), every frame:
dir.set(0, 0, 0);   // nothing held: length 0, so movePlayer returns early
dir.normalize();
player.position.addScaledVector(dir, 4 * dt);
player.rotation.y = Math.atan2(dir.x, dir.z);
player.position.x = THREE.MathUtils.clamp(player.position.x, -4.5, 4.5);   // and the same for z
tiltCamera(dt);   // mouse.x, mouse.y → camera slides, then lookAt(player)
  1. Turn Normalize diagonals off, then hold W and D together and watch Measured speed. It reads about 5.66 u/s while the Speed slider says 4.0, because the direction (1, 0, -1) is 1.41 long and the chip flags it "(diagonal!)". Let go, turn Normalize back on, and hold W and D again: 4.00 u/s, the same as driving straight. That one dir.normalize() line is the whole difference.
  2. Hold W, then click anywhere outside the stage while still holding it, then let go. The cube stops the instant you click away, even though your finger is still on the key. That is the blur handler clearing every switch. To feel the bug it prevents, imagine it gone: the keyup would go to the page, not the stage, and keys.KeyW would stay true until you focused the stage and pressed W again. Now turn Arena clamp off, drive off the edge of the grid, and press Reset player.
  3. Press and hold the D-pad's up arrow, or the W chip's real key, and compare the key row. The same W chip lights either way, and the same keys['KeyW'] = true appears in the live code. The loop cannot tell a button from a key, which is exactly the point. Then turn off Turn to face and drive in a square: the cube slides sideways like a hockey puck because rotation.y is no longer being set.

Watch Out

Common mistakes

Input bugs feel random, because they depend on how fast you type, which keyboard you own, or where you clicked last. Each of these four has a one-line cause.

Moving inside keydown

The player jumps forward, freezes for half a second, then stutters along at a speed set by the operating system's key-repeat rate. Holding two keys does not move diagonally.

Fix: the handler only writes keys[e.code] = true. The animation loop checks the object every frame and moves by speed * dt. Events flip switches; the loop reads them.

Using e.key instead of e.code

Everything works until someone presses Shift or has Caps Lock on: e.key becomes 'W' instead of 'w' and the check fails. On a French AZERTY keyboard the W key is not even where you think it is.

Fix: compare e.code, which names the physical key ('KeyW', 'ArrowUp', 'Space') and ignores Shift, Caps Lock, and layout. Use e.key only when you care about the character typed, such as in a chat box.

preventDefault: too little or too much

Too little: the arrow keys drive the cube and scroll the page, so the game slides out of view. Too much: a preventDefault() on every key on window breaks Tab, F5, and Ctrl+R for the whole site.

Fix: listen on the focusable stage, not on window, and call e.preventDefault() only for the keys in your GAME_KEYS list. Keys you do not use fall through untouched, and nothing is captured unless the stage is focused.

Sticky keys after alt-tab

You hold W, switch windows, and come back to find the player has driven itself into a wall and is still going. The keyup happened in the other window, so your stage never heard it.

Fix: on the stage's blur event, set every entry in keys to false. Losing focus means "assume nothing is held." The D-pad needs the same care: clear on pointercancel and pointerleave, not just pointerup.


Your Turn

Check your understanding

A friend's game has a bug: the player moves noticeably faster when walking diagonally than when walking straight. In one sentence, what is wrong, and what is the one-line fix?

Your answer:

Sample answer: when two keys are held the direction vector is (1, 0, -1), which is √2 ≈ 1.41 long instead of 1, so multiplying it by speed moves 41% too far; call dir.normalize() before addScaledVector(dir, speed * dt) so every direction is exactly 1 unit long.


Check Yourself

Quick quiz

1. Why keep a key-state object instead of moving the player inside the keydown handler?

2. A player reports that WASD stops working whenever Caps Lock is on. Which line is the likely cause?

3. What does dir.normalize() change about the direction vector?

Keep learning

You are driving now. You can record which keys are held in a key-state object, read it every frame to move by speed * dt, normalize the direction so diagonals are fair, turn the player to face its travel, capture keys only when the stage is focused, and read the mouse as -1..1 coordinates. Next, movement stops being instant: easing and tweening make things glide, bounce, and settle instead of snapping.

Part of the Games and Animations with Three.js tutorial series.