Need help with the keyPressed () function

So I am trying to write code that changes a variable when I press a certain key. The problem is, the keyPressed() function isn’t detecting any key presses. What am I doing wrong? My code:

var x, y;
var shape;

function setup() {
  createCanvas(400, 400);
  x = 0;
  y = 0;
  shape = 0;
}
function draw() {
  background(0, 0, 0, 20);
  if (shape == 0) {
    followShape0();
  }
  if (shape == 1) {
    followShape1();
  }
}
function keyPressed() {
  if (key == 'a') {
    shape = 1;
    print('a');
  }
if (key == 'b') {
    shape = 0;
    print('b');
  }
}
function followShape0() {
  ellipse(x, y, 20, 20);
}
function followShape1() {
  beginShape();
  vertex(x, y);
  vertex(x - 20, y);
  vertex(x - 20, y - 20);
  vertex(x, y - 20);
  endShape(CLOSE);
}
function mouseMoved() {
  x = mouseX;
  y = mouseY;
}
1 Like

You don’t have to call it

It starts automatically

Sorry, I meant that the function won’t detect my key presses, no matter where I put the function.

try:

if(keyPressed && key == 'a'){}
1 Like

This worked! Thank you.