How do you get each ball to respond individually to the mouse?

Hi, I was working on this today and I encountered a problem. What I want to do is to get each ball to follow the mouse when the mouse is within touching distance of the ball. What I cant get to work is to get each ball to do this individually. Instead, all of the balls follow my mouse at once as soon as the mouse is within touching distance of one ball.

Ball[] balls= new Ball[5];


void setup(){
size(window.innerWidth,window.innerHeight);
background(0);
for (int i = 0; i<balls.length; i++){
    balls[i]=new Ball();
}
 }

void draw(){
background(0);
for (int i = 0; i<balls.length; i++){
    balls[i].create();
    balls[i].move();
}

}


 class Ball{
float a;
float b;
int col = 255;


Ball(){
    a = random(max(window.innerWidth,window.innerHeight));
    b = random(min(window.innerWidth,window.innerHeight));
}

float d = dist(a,b,mouseX,mouseY);


void create(){
    fill(col);
    ellipse(a,b,25,25);
}

void move(){
    if (d<25){
        a=mouseX;
    }
}
}
Tagged:

Answers

  • Please check https://processing.org/reference/size_.html for proper definition of sketch size variables.

    Also, move line 33 inside your move() function in line 41.

    Kf

  • edited May 2017

    @seanpoh9321 -- re:

    float d = dist(a, b, mouseX, mouseY);
    

    The reason that, as @kfrajer points out, you can't do this, is that the code is called only once when a new Ball is created.

    class Ball {
      float a;
      float b;
      float d;
      int col = 255;
      Ball() {
        a = random(max(width, height));
        b = random(min(width, height));
      }
      void create() {
        fill(col);
        ellipse(a, b, 25, 25);
      }
      void distance(){
        d = dist(a, b, mouseX, mouseY);
      }
      void move() {
        distance();
        if (d<25) {
          a=mouseX;
          b=mouseY;
        }
      }
    }
    

    Also, try this in move if you want a sense of about how many balls are following the mouse:

          a=mouseX+random(10);
          b=mouseY+random(10);
    

    Or, to non-overlap the balls without all that bouncing around, give each Ball an xoff and yoff variable which is randomly set in the Ball constructor and then used in move.

Sign In or Register to comment.