Is there a more concise way to alternate shape and background colour with Java in Processing?

Viewed 53

In Processing, I need the rectangle in the middle of the window appear as purple and the background yellow when the mouse is hovering within the rectangle. When the mouse is anywhere else on the screen (touching the background) the rectangle should be yellow and the background should be purple. I've achieved my goal, but am wondering if there's a more concise way to write this code, or if there are alternative approaches?

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

void draw()
{
  background(205, 86, 219); // purple
  rectMode(CENTER);
  fill(231, 240, 111); // yellow
  rect(250, 250, 250, 200);
 if (mouseX >= 125 && mouseX <= 375 && mouseY >= 100 && mouseY <= 300)
 {
   background(231, 240, 111); // yellow
  fill(205, 86, 219); // purple
  rect(250, 250, 250, 200);
}
}
1 Answers

Create 2 color objects with the 2 colors:

color color1 = color(231, 240, 111); 
color color2 = color(205, 86, 219); 

Set a boolean variable when the mouse is on the rectangle:

boolean onRect = mouseX >= 125 && mouseX <= 375 && mouseY >= 100 && mouseY <= 300;

Use the ternary (?:) operator to select the color dependent on the state of onRect:

background(onRect ? color1 : color2);
fill(onRect ? color2 : color1);

Complete example:

color color1 = color(231, 240, 111); 
color color2 = color(205, 86, 219); 

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

void draw() {
    boolean onRect = mouseX >= 125 && mouseX <= 375 && mouseY >= 100 && mouseY <= 300;
    background(onRect ? color1 : color2);
    rectMode(CENTER);
    fill(onRect ? color2 : color1);
    rect(250, 250, 250, 200);
}
Related