Example 4-3 in the previous chapter moved a circle across the window. Change the sketch so that the circle only starts moving once the mouse has been pressed. Use a boolean variable.

boolean __________ =  _________;  
int circleX = 0;  
int circleY = 100;

void setup()  {   
  size(200,200);  
}   

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

void mousePressed()  {   
  ____________________________________  
}
    
Example
// Learning Processing
// Daniel Shiffman
// http://www.learningprocessing.com

// Exercise 5-8: Example 4-3 in the previous chapter moved a circle across the window. Change the sketch so that the circle only starts moving once the mouse has been pressed. Use a boolean variable.

// Boolean variable starts as false
boolean going = false;

// Location of circle
int circleX = 0; 
int circleY = 100; 

void setup() { 
  size(200,200); 
  smooth();
} 
void draw() { 
  background(255); 
  
  // Draw the circle
  stroke(0); 
  fill(175); 
  ellipse(circleX,circleY,50,50); 
  
  // Only move the circle when "going" is true
  if (going) {
    circleX = circleX + 1;
  }
} 

// Set going to true when the mouse is pressed!
void mousePressed() { 
  going = true;
} 
  • Peter

    for sake of exercise I found it interesting to do slightly altered versions of the code in order to

    a) let the circle stop at another click of the mouse
    or
    b) let the circle move on only as long as the mouse is pressed

    it’s rather easy to do once you understand this kind of boolean variables.

  • Jinieheo

    missing excercise 5-7.. :)

  • Diego

    boolean but = false;

    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 (but){

    circleX = circleX + 1;

    }

    // to apear from the outer side

    if (circleX == 225){

    circleX = -25;

    }

    }

    void mousePressed() {

    but = !but;

    }