1

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);
        }
    }
}
Daniel
  • 19
  • 8
Kai Harris
  • 21
  • 1

1 Answers1

2

You made a small mistake, but it took me a while to get it as well :P In your glow function you set the global colour, not for a single bubble.

So I propose to adapt your Bubble class as follows: remember the colour of the bubble, and then when doing the show of all bubbles, you draw the bubble in the assigned colour, depending on whether or not it was clicked.

class Bubble {
    constructor(x, y, r) {
        this.x = x;
        this.y = y;
        this.r = r;
        this.color = color(255,255,255);
    }

    move() {
        this.x = this.x + random(-1, 1);
        this.y = this.y + random(-1, 1);
    }

    show() {
        noStroke();
        fill(this.color);
        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) {
            this.color = color(244, 220, 66);
        }
    }
}

See example

nathanvda
  • 49,707
  • 13
  • 117
  • 139