Read the mouse position, check if keys are pressed, and respond to user input. These let you make interactive programs and games!
A variable that always holds the current X position of the mouse on the canvas.
Returns: number
function setup() {
size(400, 200);
}
function draw() {
background("white");
fill("dodgerblue");
noStroke();
circle(mouseX, 100, 30);
fill("black");
textSize(14);
text("mouseX: " + Math.round(mouseX), 10, 10);
}A variable that always holds the current Y position of the mouse on the canvas.
Returns: number
function setup() {
size(400, 200);
}
function draw() {
background("white");
fill("tomato");
noStroke();
circle(200, mouseY, 30);
fill("black");
textSize(14);
text("mouseY: " + Math.round(mouseY), 10, 10);
}A variable that is true when the mouse button is held down, and false when it's not.
Returns: boolean
function setup() {
size(400, 200);
}
function draw() {
if (mouseIsPressed) {
background("tomato");
fill("white");
} else {
background("white");
fill("black");
}
textSize(24);
text(mouseIsPressed ? "Pressed!" : "Click me!", 130, 85);
}A variable that holds the most recently pressed key as a string, like "a", "Enter", or " " (space).
Returns: string
let lastKey = "(none yet)";
function setup() {
size(400, 200);
}
function draw() {
background("white");
fill("black");
textSize(24);
text("Last key: " + lastKey, 80, 85);
}
function keyPressed() {
lastKey = key;
}A variable that is true when any key is held down, and false when no keys are pressed.
Returns: boolean
function setup() {
size(400, 200);
}
function draw() {
if (keyIsPressed) {
background("mediumseagreen");
fill("white");
} else {
background("white");
fill("black");
}
textSize(20);
text("Hold any key!", 120, 85);
}Checks if a specific key is currently held down. Great for smooth game controls where you need to check multiple keys at once.
| Parameter | Type | Description |
|---|---|---|
k | string | The key to check, like "ArrowUp" or "a" |
Returns: true if the key is held down, false if not
let x = 200, y = 100;
function setup() {
size(400, 200);
}
function draw() {
background("white");
if (keyIsDown("ArrowLeft")) x -= 3;
if (keyIsDown("ArrowRight")) x += 3;
if (keyIsDown("ArrowUp")) y -= 3;
if (keyIsDown("ArrowDown")) y += 3;
fill("dodgerblue");
noStroke();
circle(x, y, 20);
fill(150);
textSize(12);
text("Use arrow keys to move!", 120, 190);
}