If i click on the first ball, the second shows up as selcted. if i click on the second one the third one shows up as selected and so on.
But the boolean value is set correctly.
I can not find the problem in the code, it should be some logic error.
I appreciate any help, thank you.
have fun with this paradox ;)
my sketch.js
let balls = [];
let ballAmount = 3;
function setup() {
let red = color(255, 0, 0);
let green = color(0,255,0);
let blue = color(0,0,255);
let colors = [red, green, blue];
createCanvas(innerWidth, innerHeight);
noStroke();
for (let i = 0; i < ballAmount; i++) {
let tempX = 200 + (100 * i);
balls.push(new Ball(tempX, 200, 20, colors[i]));
}
}
function draw() {
background(0);
balls.forEach((ball) => {
ball.show();
});
}
function mousePressed() {
print(balls);
balls.forEach((ball) => {
ball.clicked();
});
}
my ball.js (class)
class Ball {
constructor(x, y, r, color){
this.pos = new p5.Vector();
this.pos.x = x;
this.pos.y = y;
this.r = r;
this.isSelected = false;
this.ballFill = color;
}
show() {
fill(this.ballFill);
ellipse(this.pos.x, this.pos.y, this.r * 2);
if (this.isSelected){
stroke(255, 255, 0);
strokeWeight(4);
} else {
noStroke();
}
}
clicked() {
let d = dist(mouseX, mouseY, this.pos.x, this.pos.y);
if (d <= this.r) {
this.isSelected = true;
} else {
this.isSelected = false;
}
}
}
Three notes...
Please be more elaborate in your question. Luckily your code kind of speaks for itself, but otherwise I would have had no idea what you were actually asking. Your post description was 'reasonable', but the title is kind of abhorrent.
You seem to be drawing your ellipses with the idea that r is half the radius, thus you multiply the r by 2. You should use ellipseMode(RADIUS) instead so it's more clear that that's the behavior you want. That lets you input the radius as half the width of the circle, like you're using your r. See this page for more information.
The reason you always outline the 'next' ball instead of the one you clicked is because you draw the ball BEFORE changing the stroke values:
this
show() {
fill(this.ballFill);
ellipse(this.pos.x, this.pos.y, this.r);
if (this.isSelected){
stroke(255, 255, 0);
strokeWeight(4);
} else {
noStroke();
}
}
should be
show() {
fill(this.ballFill);
if (this.isSelected){
stroke(255, 255, 0);
strokeWeight(4);
} else {
noStroke();
}
ellipse(this.pos.x, this.pos.y, this.r);
}
You were drawing the selected ball with stroke disabled, then you enabled the stroke, then you drew your next, unselected ball WITH the stroke you just enabled, after which you then disabled the stroke again.