Lesson 2 of 10
Keyboard state
- 14 min
- 5 checks
- 3 hints
- Go to task
Goal
Track which keys are held down on every frame
Explanation
Your first instinct is usually to move the player inside a keydown listener, and that's the wrong way to do it. The event fires once, pauses for about half a second, then repeats at a rate set by the operating system, not by your game. The movement stutters, and only the last key you pressed keeps repeating.
That's why games keep the two apart. The listeners record the keys held down right now in a keys object, setting true on keydown and false on keyup. Then the loop reads that state on every frame and moves the player using dt.
Watch out for diagonal movement. If the player holds the right and down arrows together, they move a full step along each axis, so they cover √2 times the distance of a straight move and end up about 41% faster. The fix is to divide the direction vector by its length, Math.hypot(dx, dy), before multiplying it by the speed.
Your task
Fill keys from the keydown and keyup events on window, using the key name e.key. Then write applyInput(player, keys, dt) so the four arrow keys move the player at player.speed pixels per second, the up arrow decreases y, and a diagonal move covers the same distance as a straight one. To try it, click the preview and move the player with the arrow keys.
Checks
5 checks- keydown records the key in keys
- keyup sets the key back to false
- The right arrow moves the player by speed × dt
- The up arrow decreases y
- Diagonal movement is no faster than straight movement