keyCode()
The `keyCode()` function in p5.js returns the code of a key pressed on the keyboard. Creative coders use it to detect specific key presses, enabling interactive experiences in their art. For instance, imagine a generative art piece that changes colors or patterns based on user input; `keyCode()` allows the artist to respond dynamically to the viewer's actions.
๐ p5.js Reference โ๐ง See The Whole Picture
Imagine your keyboard as a map, where each key is a location with a corresponding code. When you press a key, it sends a signal to your sketch, allowing it to react accordingly. The `keyCode()` function acts like a GPS, helping your code navigate through the various keys to find out which one was pressed.
๐ Visual Learner's Guide
The Big Picture:
When you run this code, pressing the space bar makes a circle appear on the canvas.
Visual Analogy:
Think of `keyCode()` as a light switch. When you flip the switch (press a key), it turns on the light (activates an action).
The Numbers Decoded:
The number 32 means the space bar. When you check for 32, youโre saying, 'If I press the space bar, do something!'
Connection Map:
The `fill()` function sets the color of the circle before it is drawn, and `ellipse()` uses both the color and the code from `keyCode()` to create the visual effect.
Common Gotcha:
Remember, `keyCode()` checks for the key itself, not just the action, so ensure youโre using the correct key code.
๐ How It Works
This diagram illustrates how your code checks for a key press using `keyCode()`, and based on the result, triggers a corresponding action.
๐ Syntax
๐ How to Read This
Read `keyCode(value)` as: Detect the key code of a key pressed on the keyboard. The parentheses are like a delivery box - you hand the function the specific key code you want to check.
keyCode(param1, param2, ...)
Example: keyCode(200, 150, 80)
๐ Different Ways to Call It
keyCode(value)
This form is used to check for a specific key code directly, allowing you to trigger specific actions based on that key.
keyCode(32)
โ This checks if the space bar (key code 32) is pressed.
keyCode(v1, v2, v3)
This form can be used to set multiple key codes, though it's less common. It's useful when you want to trigger multiple actions at once based on different keys.
keyCode(65, 66, 67)
โ This checks for the key codes corresponding to 'A', 'B', and 'C'.
โฉ๏ธ What It Returns
Type: Number
`keyCode()` hands back a number representing the key pressed. Think of it as a secret code for each key on your keyboard, which you can use to determine what action to take in your sketch.
Parameters
key
Number
required
Visualize a number like 65, which corresponds to the 'A' key on a keyboard.
This controls which key you're checking for. Typical values are based on keyboard layout, with each key having a unique code.
Range: 0-255 (for standard keys, though many keys have specific codes outside this range).
32 โ Represents the Space key.
65 โ Represents the 'A' key.
90 โ Represents the 'Z' key.
๐ก How Parameters Work Together
The parameter you pass to `keyCode()` is like a key to a secret door; it opens up specific actions in your sketch. If you check for the value 32, you're asking if the space bar was pressed, which might trigger a pause in your animation.
๐ป Working Example
// Complete working example with comments
function setup() {
createCanvas(400, 400);
}
function draw() {
background(220);
// Check if the space bar is pressed
if (keyIsPressed && keyCode === 32) {
fill(100, 200, 255);
ellipse(width / 2, height / 2, 100, 100); // Draw a circle if space is pressed
}
}
Try This Code โ
โ๏ธ How It Works
When you call `keyCode()`, it checks the current state of keyboard inputs. If a key is pressed, it retrieves the code associated with that key and can be used in conditions to trigger actions in your sketch. The rendering pipeline then updates the canvas based on these actions, providing immediate visual feedback.
๐ Learn Prompt Patterns
These patterns help you write better prompts for ANY function:
๐ญ Persona Pattern
Tell the AI to act as a specific type of creator
"Act as a creative coder making generative art. Use keyCode() to create a colorful explosion when the space bar is pressed."
Why it works: Giving the AI a persona helps it understand the CONTEXT and style you want.
๐ Recipe Pattern
Ask for step-by-step instructions
"Give me step-by-step code to use keyCode() to create a bouncing ball that stops when the space bar is pressed."
Why it works: Breaking down into steps helps you understand each part and learn incrementally.
๐ Template Pattern
Provide a structure for the AI to fill in
"Use this template: setup creates a canvas, draw uses keyCode() with specific parameters to make a character move left and right based on arrow keys."
Why it works: Templates give the AI clear constraints, resulting in more predictable output.
๐ Refinement Pattern
Start simple and iterate
"Start with a basic keyCode() example that draws a circle. Then I'll ask you to add color, size, and animation."
Why it works: Building up gradually helps you understand each addition and not get overwhelmed.
๐ฏ Direct Prompts - Name the Function
Tell the AI exactly which function to use:
"Use keyCode() to create a sketch that changes the background color when the 'B' key is pressed."
๐ก Why this is good: This prompt gives a clear visual goal and context, allowing the AI to focus on creating an engaging interaction.
๐ What you learn:
// Full working code example
let bgColor = 220;
function setup() {
createCanvas(400, 400);
}
function draw() {
background(bgColor);
if (keyIsPressed && keyCode === 66) { // 66 is 'B'
bgColor = color(random(255), random(255), random(255));
}
}
"Use keyCode() to draw a rectangle that moves left and right with arrow keys."
๐ก Why this is good: This structure helps learners understand the function step-by-step, reinforcing the relationship between key presses and visual actions.
๐ What you learn:
// Full working code example
let x = 200;
function setup() {
createCanvas(400, 400);
}
function draw() {
background(220);
rect(x, height / 2 - 25, 50, 50);
if (keyIsPressed) {
if (keyCode === LEFT_ARROW) {
x -= 5;
}
if (keyCode === RIGHT_ARROW) {
x += 5;
}
}
}
๐ฎ Indirect Prompts - Describe What You Want
Don't name the function - see if the AI figures out to use keyCode():
"Create a sketch where pressing a key makes a shape appear, without mentioning keyCode()."
๐ก Why this is good: This teaches how to express visual goals without focusing on specific function names, encouraging creative problem-solving.
๏ฟฝ What you learn:
// Code showing AI chose keyCode()
let shapeVisible = false;
function setup() {
createCanvas(400, 400);
}
function draw() {
background(220);
if (shapeVisible) {
ellipse(width / 2, height / 2, 50, 50);
}
}
function keyPressed() {
shapeVisible = true;
}
๐ผ๏ธ See It In Real Sketches
How keyCode() is used in actual gallery sketches:
Interactive Color Changer
In this sketch, `keyCode()` is used to change the background color when specific keys are pressed, creating an interactive experience.
// Relevant code showing the function in context
function keyPressed() {
if (keyCode === 82) { // R for Red
background(255, 0, 0);
} else if (...
๐ Fun Function Combinations
Try asking the AI to combine keyCode() with these:
keyCode() + ellipse()
โ Draws a circle that changes position based on keyboard input.
Try: "Create a sketch where the circle moves with arrow keys using keyCode()."
// 5-10 lines showing the combination
let x = 200;
let y = 200;
function setup() {
createCanvas(400, 400);
}
function draw() {
background(220);
ellipse(x, y, 50, 50);
if (keyIsPressed) {
if (keyCode === UP_ARROW) { y -= 5; }
if (keyCode === DOWN_ARROW) { y += 5; }
if (keyCode === LEFT_ARROW) { x -= 5; }
if (keyCode === RIGHT_ARROW) { x += 5; }
}
}
โ ๏ธ Common Mistakes & Fixes
โ Mistake: Not checking for keyIsPressed before checking keyCode.
๐ค Why it's wrong: This can lead to errors or unexpected behavior as the code may try to read the key code when no key is pressed.
โ Fix: Always use an if statement to check if a key is pressed before checking keyCode.
๐บ๏ธ Learning Path
๐ก Project Ideas
- Create a simple game where players control a character using the keyboard.
- Build an interactive art piece that changes colors with different key presses.
๐ค Ask xelsed-alpha6 to Explain
"Explain what keyCode() does in p5.js"
Try this prompt in p5js.AI to see how the AI explains it!
Try in p5js.AI โ๐ก Prompt AI to Write Code Using keyCode()
"Create something using keyCode()"
๐ง Ask AI to Help Debug
"My keyCode() isn't working, help me debug"
โจ Creative Combinations with AI
"Combine keyCode() with other functions for interesting effects"
๐ Related Functions
Ready to Try keyCode()?
Open p5js.AI and ask the AI to help you use keyCode() in your own creative project.
Start Coding with AI โ