We are about to switch to a new forum software. Until then we have removed the registration on this forum.
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;
}
}
}
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
@seanpoh9321 -- re:
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.
Also, try this in move if you want a sense of about how many balls are following the mouse:
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.