Solving an exercise in Dan Shiffman "Learning Processing"

Trying to solve Exercise 5-8 (p.83) in D. Shiffman book “Learning Processing”

Keep getting an error message: "unexpected token: void"

Goal: circle starts moving in sketch once the mouse has been pressed.

Here is my code:

boolean moving = true;

int circleX = 0;
int circleY = 100;

void setup() {
  size(200, 200);
}
void draw() {
  background(100);
  stroke(255);
  fill(0);
  ellipse(circleX, circleY, 50, 50);

  if (moving) {
    circleX = circleX+1;
  }
 void mousePressed() {
    moving = !moving;
  }
}

What am i missing?
Thank you!

1 Like

Hey there, You got your mousePressed as a void statement, but it is inside the draw() function. Take it out of the draw(), and it should work:

boolean moving = true;

int circleX = 0;
int circleY = 100;

void setup() {
  size(200, 200);
}
void draw() {
  background(100);
  stroke(255);
  fill(0);
  ellipse(circleX, circleY, 50, 50);

  if (moving) {
    circleX = circleX+1;
  }
}

void mousePressed() {
  moving = !moving;
}
1 Like

Thank you!! That worked. :slightly_smiling_face:

Note that there are two things called mousePressed – a function, which is called whenever the mouse is pressed, and a variable, which is true whenever the mouse is pressed.

Use the variable in draw – use the function outside.

1 Like

Thank you! Being new to coding, this further clarification of the function vs the variable usage is very helpful!! Much appreciated.