Keyboard event handling - Griffith-ICT/1701ICT-Creative-Coding GitHub Wiki

Many games use some form of keyboard input whether it is from a specialised game controller or simply the arrow keys on a keyboard.

Keyboard event handling is very similar to mouse event handling. We can either test if a key is currently pressed, or write a function which will be called when a key is pressed.

Keyboard Event Handling

p5.js provides the following keyboard event handler functions:

  • keyPressed()
  • keyReleased()
  • keyTyped()

When the one of these functions is called we can check what the key is by comparing either the key or the keyCode variable. The key variable will provide the ASCII character of the letter, number, or punctuation pressed, whereas the keyCode is used to determine if an arrow key, or return, tab, escape, etc. characters are pressed.

function keyPressed() {
  if (keyCode === LEFT_ARROW) {
    // Do something
  } 
}

Note: === returns true if keyCode has the value LEFT_ARROW. === and == are very similar they both test if the values are the same, however == will attempt to convert the type of the value first, whereas === won't. For example, 5 == "5" will be true as the "5" will be converted to a number. 5 === "5" will never be true as it won't try to convert the string to a number. It is generally good practise to use === so there aren't any surprise conversions.