Search code examples
processing

Variables and conditions in processing


Just wondering if I want to do a loop to make every time I mousePressed to draw a circle and each time fill with 3 different colour eg yellow orange and blue and so on I use for(int countmouseClick=n; n<=3 ; n++) how should I finish the rest? Should I reset n if n=3 to n= 0?. The circles can stay on the canvas Not sure if it correct.

void mousePressed(){
   for ( int count=0; n<= 2; n++){
    fill(255,0,0);
    fill(0,255,0);
    fill(0,0,255);
    }
   circle(mouseX,mouseY,20);

}

//i have adopted the idea of %, it telling me the variable n doesn't exist, why is this

int count;
void setup(){
  size(400,400);
  background(255);
}

void draw(){
}

void mousePressed(){
  int count=n;
  if(n>2){              //reset mouse click to 0
           n=0;
    }
  for(int n= 0;n<=2;n++){//count mouseclicked, if n<=2, n=n+1
  if(n%3=0){
    fill(255,0,0);
  }else if (n%3=1){
    fill(0,255,0);
  }
   else {
    fill(0,0,255);
}

circle(mouseX,mouseY,20);
   }
}

Solution

  • a better way of writing the code is to write a helper function which takes countmouseclick and return the color

    you can read these articles for understanding the code below

    https://processing.org/reference/modulo.html https://processing.org/reference/switch.html

    Color getColor(int countMouseClick){
    
    switch(countMouseClick%3) {
      case 0:
        return COLOR.ORANGE;
      case 1:
        return COLOR.YELLOW;
        break;
      case 2:
        return COLOR.BLUE;
      default:
        return COLOR.GREEN;
    
    }