Like the mouse events we covered in our first lessons on interaction, we can also use events in JavaScript to detect user interaction with the keyboard.
We can detect whether the user has pressed a key down, released a key and determine which key was pressed, using p5 environment variables and boolean logic.
keyIsPressed
The following example will simply display whether or not a user is pressing any key on the keyboard using the keyIsPressed
environment variable.
This is a boolean value, a key is either being pressed or not, so keyIsPressed
is either true
or false.
key
Once we have determined that a key is being pressed, we may need to know which key is being pressed.
The key
variable saves the value of whichever key was most recently pressed, like the mouseX
variable saves the most recent x position of the mouse.
Notice that this code has one if
statement inside of another. We are testing two different sets of conditions.
Be careful to make the curly brackets match here. Use Beautify in Brackets if it doesn't look right.
keyCode
keyCode
variable. Use keycode.info to test which key is which keyCode
.
keyPressed
Like the mousePressed
function, we can use keyPressed
in cases where we just want to react to a key press with a function.
Since we covered sound earlier this week, let's use a key press to trigger a sound file.
This example will trigger a recording of chickens I found on FreeSound.org.
There are other functions like keyReleased
for other keyboard related events.
Make sure to check out the