Page 2: Interaction and Variables

2. Interaction and Variables

Making your sketches responsive to user input is a key part of creative coding. p5.js provides easy ways to access mouse, keyboard, and other system data.

2.1. Mouse Interaction

Use system variables like mouseX, mouseY, pmouseX, pmouseY to get the current and previous mouse positions. Functions like mousePressed(), mouseReleased() also help.

function draw() {
  background(220);
  line(pmouseX, pmouseY, mouseX, mouseY); // Draw a line following the mouse
  
  if (mouseIsPressed) {
    fill(0); // If mouse is pressed, fill black
  } else {
    fill(255); // Otherwise, fill white
  }
  ellipse(mouseX, mouseY, 30, 30); // Draw a circle at mouse position
}
// Optionally:
function mousePressed() {
  console.log("Mouse clicked!");
}

2.2. Keyboard and System Variables

Respond to keyboard input using keyIsPressed or functions like keyPressed(). Utilize variables like width, height, frameCount, and random() for dynamic behavior.

let circleX;

function setup() {
  createCanvas(400, 400);
  circleX = width / 2;
}

function draw() {
  background(220);
  
  if (keyIsPressed && key === 'a') {
    circleX -= 5; // Move left if 'a' is pressed
  } else if (keyIsPressed && key === 'd') {
    circleX += 5; // Move right if 'd' is pressed
  }
  
  ellipse(circleX, height / 2, 50, 50);
  
  // Example of using frameCount and random()
  fill(random(255), random(255), random(255), 100); // Random translucent color
  rect(10, 10, frameCount % 100, frameCount % 100); // Size changes with frameCount
}