Improved Keyhandling Logic

When talking about our current logic for dealing with the keyboard events, I mentioned that we are using a less-than-ideal solution. To see why, go back to your example and press and hold the Up and Right arrow keys at the same time. What you would expect to see is your triangle moving diagonally. What you actually see is your triangle moving in only one direction - either right or up. That isn’t what we want!

The reason for this bizarre behavior is because we are using a switch statement to figure out which arrow key was pressed. There is nothing wrong with this general approach, for switch statements are far less verbose than if/else-if statements for checking which condition happens to equate to true. For many general cases, this is fine. How often are people going to hold down multiple keys at the same time? As it turns out, for the interactive/game-ey things that we are doing, pressing multiple keys will be a common occurrence. Pressing the Up and Right arrows on the keyboard at the same time is the equivalent of pushing a joystick diagonally. Don’t tell me you’ve never done that before!

The solution is to change how we check for which key was pressed. Replace your existing addEventListener call and moveSomething function with the following instead:

Get hands-on with 1200+ tech skills courses.