Rollover not working when applied in an array of circles

Hi all, coding with Processing for just over a month only so lots of things to learn :sweat_smile:

I’ve created a simple rollover so when the mouse is within the circle it changes color. It works… however when adjusting the setup() loop to instead of 1 circle at x=250, y=250 I make x,y a function of i I do get multiple circles but when I roll over one, it’s the adjacent circle the one changing the color :joy:. Any ideas? Full code below. Appreciate any help!

Button[] buttons = new Button[4];
boolean rollover = false;

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

  //this loop works with i.e. x=250, y=250, but not like this ;(
  for(int i = 0; i < buttons.length; i++) {
    buttons[i] = new Button(100+100*i, 100+100*i, 50, color(#BC021B), color(#396AE3));
  }
}

void draw() {
  background(255);

  for (int i = 0; i < buttons.length; i++) {
    buttons[i].display();
    buttons[i].withinCircle();
  }
}

  class Button {
    //variables
    float x;
    float y;
    float diam; //width and height = diameter for circles
    color c;
    color c1;
    
    //constructor
    Button(float tempX, float tempY, float tempDiam, color tempC, color tempC1) {
      x = tempX;
      y = tempY;
      diam = tempDiam;
      c = tempC;
      c1 = tempC1;
    }
  
    //methods
    //function that displays the circle and fills the color based on condition
    void display() {
      if(rollover) {
        fill(c);
      } else {
        fill(c1);
        }
      
      noStroke();
      ellipseMode(CENTER);
      ellipse(x,y,diam,diam);
    }
    //function that calculates if the mouse coordinates are within the circle or not
    void withinCircle() {
      float distance = dist(x,y,mouseX,mouseY);
      if(distance < diam/2) {
        rollover = true;
      } else {
        rollover = false;
        }
    }
  }

Hello @Erif,

Give consideration to the order of these:

Which one do you want to do first?

:)

1 Like

Ooooh… magic!! :sparkles:
I need to first calculate if the mouse is within the circle then display the circle with the rollover condition.
It works perfectly by inverting those 2 function calls.
Thanks a lot @glv

2 Likes