We will create an event handler in lib/game/event.ts
. The event handler must set the correct movement direction in the state. The time handler will then use this to update the direction of the player. The step can only do that when the player is aligned to the grid. If the player is between two fields on the grid, we will not change the direction of the player, since he will then probably head into a wall.
An event provides the key code of the pressed or released key. We can get this code of a certain character with "x".charCodeAt(0)
(where x
is the character). The key codes of left, top, right, and bottom are 37, 38, 39, and 40.
First, we must create a helper function that transforms a key code to the Movement enum
that we defined earlier. We store the different keys that we use in a new enum
:
import { KeyEvent, KeyEventKind } from "../framework/event"; import { State, Movement } from "./model"; import { update } from "./utils"; ...