Keyboard Input
Learn how to detect key presses and create keyboard controls for your games.
Basic Key Detection
The simplest way to detect keys is using the keyPressed() function:
function setup() {
createCanvas(400, 400);
}
function draw() {
background(220);
fill(0);
textAlign(CENTER, CENTER);
text("Press any key!", 200, 200);
}
function keyPressed() {
console.log("Key pressed:", key);
}
Breaking it down
keyPressed()- Automatically called once when any key is pressedkey- Stores the character of the key that was pressed (like 'a', 'B', '5')- Runs outside of
draw()- it's a special p5.js function
Detecting Specific Keys
Check which key was pressed using the key variable:
function keyPressed() {
if (key === 'a') {
console.log("A key pressed!");
} else if (key === 'b') {
console.log("B key pressed!");
}
}
Breaking it down
- Use
===to compare the key with a character - Case sensitive -
'a'is different from'A' - Works with letters, numbers, and some symbols
Arrow Keys & Special Keys
For arrow keys and special keys, use keyCode:
let x = 200;
let y = 200;
function draw() {
background(220);
fill(100, 150, 250);
circle(x, y, 50);
fill(0);
textAlign(CENTER);
text("Use arrow keys to move", 200, 380);
}
function keyPressed() {
if (keyCode === LEFT_ARROW) {
x = x - 10;
} else if (keyCode === RIGHT_ARROW) {
x = x + 10;
} else if (keyCode === UP_ARROW) {
y = y - 10;
} else if (keyCode === DOWN_ARROW) {
y = y + 10;
}
}
Breaking it down
keyCode- Stores a number representing special keysLEFT_ARROW,RIGHT_ARROW,UP_ARROW,DOWN_ARROW- Built-in p5.js constants- Moving left/up decreases position
- Moving right/down increases position
Smooth Movement (Continuous Input)
Make movement smoother by checking if keys are held down in draw():
let x = 200;
let y = 200;
let speed = 3;
function draw() {
background(220);
// Check which keys are currently pressed
if (keyIsDown(LEFT_ARROW)) {
x = x - speed;
}
if (keyIsDown(RIGHT_ARROW)) {
x = x + speed;
}
if (keyIsDown(UP_ARROW)) {
y = y - speed;
}
if (keyIsDown(DOWN_ARROW)) {
y = y + speed;
}
fill(100, 150, 250);
circle(x, y, 50);
}
Breaking it down
keyIsDown(keyCode)- Returns true if the key is currently held down- Checked in
draw(), so it updates every frame (smooth movement) - Use separate
ifstatements (notelse if) to allow diagonal movement - Adjust
speedto control how fast the object moves
WASD Controls
Create WASD controls as an alternative to arrow keys:
let x = 200;
let y = 200;
let speed = 3;
function draw() {
background(220);
// WASD movement
if (keyIsDown(65)) { // A key
x = x - speed;
}
if (keyIsDown(68)) { // D key
x = x + speed;
}
if (keyIsDown(87)) { // W key
y = y - speed;
}
if (keyIsDown(83)) { // S key
y = y + speed;
}
fill(100, 150, 250);
circle(x, y, 50);
}
Breaking it down
keyIsDown()accepts ASCII key codes- W = 87, A = 65, S = 83, D = 68
- Standard gaming controls (left hand on WASD, right on mouse)
Better WASD Using Letters
Use character comparison for cleaner code:
let x = 200;
let y = 200;
let speed = 3;
function draw() {
background(220);
// Check lowercase keys
if (keyIsDown(LEFT_ARROW) || key === 'a') {
x = x - speed;
}
if (keyIsDown(RIGHT_ARROW) || key === 'd') {
x = x + speed;
}
if (keyIsDown(UP_ARROW) || key === 'w') {
y = y - speed;
}
if (keyIsDown(DOWN_ARROW) || key === 's') {
y = y + speed;
}
fill(100, 150, 250);
circle(x, y, 50);
}
Breaking it down
||means "or" - either condition can be true- Works with both arrow keys AND WASD
- Use lowercase letters for consistency
Action Keys (Space, Enter)
Detect action keys like spacebar or enter:
let isJumping = false;
let y = 300;
let jumpSpeed = 0;
function draw() {
background(220);
// Apply gravity
if (isJumping) {
y = y + jumpSpeed;
jumpSpeed = jumpSpeed + 0.5; // Gravity
// Land on ground
if (y >= 300) {
y = 300;
isJumping = false;
jumpSpeed = 0;
}
}
fill(100, 150, 250);
circle(200, y, 50);
// Ground
line(0, 325, 400, 325);
}
function keyPressed() {
// Jump with spacebar
if (key === ' ' && !isJumping) {
isJumping = true;
jumpSpeed = -12;
}
// Alternative: ENTER key
if (keyCode === ENTER) {
console.log("Enter pressed!");
}
}
Breaking it down
- Spacebar is represented by
' '(a space character) ENTERis a built-in keyCode constant!isJumpingprevents jumping while already in the air- Negative jumpSpeed moves upward initially
Preventing Default Behavior
Some keys have default browser actions (like spacebar scrolling the page):
function keyPressed() {
// Your game logic
if (key === ' ') {
console.log("Jump!");
}
// Prevent default browser behavior
return false;
}
Breaking it down
return falseat the end ofkeyPressed()prevents default actions- Stops spacebar from scrolling the page
- Stops arrow keys from scrolling
- Important for games!
Common Patterns
Preventing Opposite Directions
Don't allow instant direction reversal (like in Snake):
let direction = 'right';
let newDirection = 'right';
function draw() {
// Update direction (do this before moving)
direction = newDirection;
// Move based on direction
// ... movement code ...
}
function keyPressed() {
if (keyCode === LEFT_ARROW && direction !== 'right') {
newDirection = 'left';
} else if (keyCode === RIGHT_ARROW && direction !== 'left') {
newDirection = 'right';
} else if (keyCode === UP_ARROW && direction !== 'down') {
newDirection = 'up';
} else if (keyCode === DOWN_ARROW && direction !== 'up') {
newDirection = 'down';
}
return false;
}
Key Combinations
Detect when multiple keys are pressed together:
function draw() {
background(220);
// Hold SHIFT to move faster
let speed = 3;
if (keyIsDown(SHIFT)) {
speed = 8;
}
// Movement with variable speed
if (keyIsDown(LEFT_ARROW)) {
x = x - speed;
}
// ... other directions
}
All Special Key Constants
BACKSPACE // Backspace key
DELETE // Delete key
ENTER // Enter key
RETURN // Return key (same as ENTER)
TAB // Tab key
ESCAPE // Escape key
SHIFT // Shift key
CONTROL // Control key
OPTION // Option/Alt key
ALT // Alt key (same as OPTION)
UP_ARROW // ↑
DOWN_ARROW // ↓
LEFT_ARROW // ←
RIGHT_ARROW // →
Tips & Tricks
- Use keyIsDown() for movement - Gives smooth, continuous movement
- Use keyPressed() for actions - One-time events like jumping or shooting
- Return false - Prevent browser from reacting to game keys
- Variable speed - Store speed in a variable for easy adjustment
- Test on different keyboards - Some keyboards have different layouts
Common Gotchas
⚠️ Case sensitivity - 'a' and 'A' are different keys
⚠️ keyPressed vs keyIsDown - One is a function, one checks state!
⚠️ Held keys auto-repeat - keyPressed() fires multiple times if key is held
⚠️ Some keys trigger browser - Always return false in keyPressed()
⚠️ Diagonal movement - Use separate if statements, not else if
Keyboard Input Summary
| Use Case | Function | Example |
|---|---|---|
| One-time action | keyPressed() | Jumping, shooting, pausing |
| Continuous movement | keyIsDown() | Walking, flying |
| Check which key | key | Letters, numbers |
| Special keys | keyCode | Arrow keys, Enter, Shift |
| Prevent browser actions | return false | Stop page scrolling |
Try It Yourself
Experiment with these ideas:
- Create a character that jumps with spacebar
- Make a two-player game with different controls (WASD vs Arrows)
- Add a "sprint" feature by holding Shift
- Create a typing game that responds to letter keys
Ready to add images to your game? Check out the Images guide! 🖼️