Circle will become larger when mouse moves on it (loop question)

Hello,

I want to create a project, when the mouse move on the circle, the circle will become larger. I can do it when it’s only one circle, but when I add a loop in it, it cannot work.

int x=-45;
int a;

void setup() {

  size(720, 720);
}


void draw() {

  background(255);
 
//loop six circle ; the distance of two circle is 45, diameter is 90, 45+90=135;
 for (int x=-45; x<675; x=x+135) {
    fill(0);
    ellipse(x, height/2, 90, 90);
  }
 
 // mouse on the circle mouse circle will have strokeWeight 

 if ((dist(x, height/2, mouseX, mouseY)<45)) {
      x=x+135;
      stroke(0);
      strokeWeight(20);
      cursor(HAND);
    } else {
      noStroke();
      cursor(ARROW);
    }
  }
1 Like

Hi xhqecho,

Can you please format your code? It is all explained in this thread: Guidelines—Tips on Asking Questions

The problem is that you are using a for loop to draw your shape but you are not having one to check the distance. So you are checking the distance with the last x value the for loop is giving you.

Consider using another loop to check the distance for each one of your circle.

Hi jb4x,

Thank you.

The distance of each is 45, I have made the six circle have same distance, it just didn’t become larger when the mouse move on it.

Working with objects makes this easy.

class Circle {
  float x, y, s;
  Circle(float ix){
    x = ix;
    y = height/2;
    s = 90;
  }
  void draw(){
    if( over() ){
      s++;
    } else if( s > 90 ){
      s--;
    }
    ellipse(x,y,s,s);
  }
  boolean over(){
    return( dist(mouseX, mouseY, x, y) < s / 2.0 );
  }
}

Circle[] circles = new Circle[5]; 

void setup() {
  size(720, 720);
  fill(0);
  for( int i = 0; i < 5; i++) circles[i] = new Circle(90 + 135 * i );
}

void draw() {
  background(255);
  for( Circle c : circles ) c.draw();
}

Normally I would walk you through developing this, but I’m pretty tired right now. So just… promise you’ll put effort in to understand this.

I get what your code is doing.

Again, you need to use another for loop to check the distance for each one of the circles.

Or use the method of @TfGuy44 using OOP. It is a cleaner way to do what you want to achieve but if you have never heard of class and object before I strongly advise you to do some reading before using the solution.

Thank you again! I will try to realize it.

Thank you for your help! I will try to understand it.