Using p5 libraries, with p5 editor.
I'm trying to change the colour of a 'bubble' in an array of 'bubbles' however, when I click on a bubble it changes all of the bubbles colours.
The glow()
function is the one that changes the colour and the mousePressed()
function checks to see if you have clicked the mouse.
var bubbles = [];
var bubbleNum = 10; //The number of bubbles on the screen
function setup() {
createCanvas(1000, 800);
for (let i = 0; i < bubbleNum; i++) {
let x = map(i, 0, bubbleNum, 0, width);
bubbles[i] = new Bubble(x, random(0, height), 30);
}
}
function draw() {
background(50);
for (let i = 0; i < bubbleNum; i++) {
bubbles[i].show();
if (mouseIsPressed) {
for (let i = 0; i < bubbleNum; i++) {
bubbles[i].move();
}
}
}
}
function mousePressed() {
for (let i = 0; i < bubbles.length; i++) {
bubbles[i].glow(mouseX, mouseY);
}
}
class Bubble {
constructor(x, y, r) {
this.x = x;
this.y = y;
this.r = r;
}
move() {
this.x = this.x + random(-1, 1);
this.y = this.y + random(-1, 1);
}
show() {
noStroke();
ellipse(this.x, this.y, this.r, this.r);
}
glow(mx, my) {
let d = dist(mx, my, this.x, this.y);
if (d < this.r) {
fill(244, 220, 66);
}
}
}