Loading...
Logo
Processing Forum

mouseClicked question

in Programming Questions  •  7 months ago  
Hello,
I am trying to create a program that displays 6 rectangles, that change color when clicked.  I have succeeded in drawing the rectangles, and the program responds when you click, but it changes the color of all of the rectangles.  I am not sure how to get the program working properly.  In the code I have included, I have the program set to change color when the upper left rectangle is pressed.  Any advice would be much appreciated!

Copy code
  1. int width = 640;
  2. int height = 480;
  3. float red_channel = 255;
  4. float green_channel = 255;
  5. float blue_channel = 255;

  6. void setup() 
  7.   {
  8.    size(width, height);
  9.   }

  10. void draw() {
  11.   
  12.   rect(0, 0, width/3, height/2);
  13.   rect((width/3), 0, width/3, height/2);
  14.   rect(width-width/3, 0, width/3, height/2);
  15.   rect(0, height/2, width/3, height/2);
  16.   rect(width/3, height/2, width/3, height/2);
  17.   rect(width-width/3, height/2, width/3, height/2); 
  18.   }


  19. void mouseClicked()
  20. {
  21.  if(mouseX < width/3 && mouseY < height/2)
  22.   {
  23.   red_channel = random(0, 255);
  24.   green_channel = random(0, 255);
  25.   blue_channel = random(0, 255);
  26.   
  27.   fill(red_channel, green_channel, blue_channel);
  28.   rect(0, 0, width/3, height/2);
  29.   } 
  30. }



Thanks,
Trevor

Replies(1)

You only have one fill() in the code. If you put unique fill()s before each rect() that would solve your problem. Like this:
Copy code
  1. fill(r1, g1, b1);
  2. rect(x1, y1, w1, h1);
  3. fill(r2, g2, b2);
  4. rect(x2, y2, w2, h2);
  5. // etc...

On a side note, width and height are built into Processing. If you delete your width and height variables then write:
Copy code
  1. size(640, 480);

Your code still work and make correct use of width and height