Wrong item in array is being edited (I think), p5.js. Help!

Hi there,
I’m trying to make an array of objects which will change fill when the mouse is inside the object. I have got it to work when it was a single object but now there are multiple there is a bug which is filling a different object to which is being hovered over by the mouse. I have tried to test intersecting in a few different places but it doesn’t make a difference. I’m new at programming and sorry if this is a very obvious mistake! Thanks in advance!

let balls = [] //making an array for Ball(s)

function setup() {
	createCanvas(600, 400);
	for (let i = 0; i <5; i ++) {  //Making n number of Balls
		let tempX = 30 + (100 * i);  //Giving x and y for starting point of Ball
		let tempY = 200;
		let b = new Ball(tempX, tempY);
		balls.push(b);
	}

}

function draw() {
	background(100);
	for (let i = 0; i < balls.length; i ++){
		balls[i].intersects(mouseX, mouseY)
		balls[i].show(); //mouse X and Y position
	}

}
class Ball {   //Making ball using tempX and tempY from setup
	constructor(tempX, tempY) {
		this.r = 20; //radius
		this.x = tempX;
		this.y = tempY;
		this.colour = (255, 0, 0); //starting colour is red
	}
	//testing the distance from the mouse x,y to the ball x,y to see if
	//mouse is inside, comparing to this.r which is the radius of ball
	intersects(mx, my) {
		let d = dist(mx, my, this.x, this.y);
		if (d < this.r) {
			this.colour = 255; //change colour if mouse is inside
		}else {
			this.colour = 0 //change colour to 0 if mouse outside
		}
	}

	show() {
		noStroke();
		ellipse(this.x, this.y, this.r * 2);
		fill(this.colour);
	}
}
		ellipse(this.x, this.y, this.r * 2);
		fill(this.colour);

These two lines are round the wrong way. You need to set the fill color BEFORE you draw the ellipse!

It’s like painting. Pick the color of paint, then paint a thing. You don’t paint something and then pick the color of paint!

2 Likes

Of course!
Thank you very much!