影响数组p5.js-Javascript中的一个对象

影响数组p5.js-Javascript中的一个对象,javascript,p5.js,Javascript,P5.js,使用p5库,使用p5编辑器。 我试图改变一系列“泡泡”中“泡泡”的颜色,但是,当我点击一个泡泡时,它会改变所有泡泡的颜色 glow()函数用于更改颜色,并且mousePressed()函数检查您是否单击了鼠标 var bubbles = []; var bubbleNum = 10; //The number of bubbles on the screen function setup() { createCanvas(1000, 800); for (let i = 0;

使用p5库,使用p5编辑器。
我试图改变一系列“泡泡”中“泡泡”的颜色,但是,当我点击一个泡泡时,它会改变所有泡泡的颜色

glow()
函数用于更改颜色,并且
mousePressed()
函数检查您是否单击了鼠标

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);
        }
    }
}
var-bubbles=[];
var bubbleNum=10//屏幕上气泡的数量
函数设置(){
createCanvas(1000800);
for(设i=0;i
您犯了一个小错误,但我也花了一段时间才弄明白:p在您的
发光功能中,您设置了全局颜色,而不是单个气泡的颜色

因此,我建议对
气泡
类进行如下调整:记住气泡的颜色,然后在对所有气泡进行
显示
时,根据是否单击气泡,以指定的颜色绘制气泡

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);
        }
    }
}
类气泡{
构造函数(x,y,r){
这个.x=x;
这个。y=y;
这个。r=r;
this.color=color(255255);
}
移动(){
this.x=this.x+随机(-1,1);
this.y=this.y+随机(-1,1);
}
show(){
仰泳();
填充(此颜色);
椭圆(this.x,this.y,this.r,this.r);
}
辉光(mx,我的){
设d=dist(mx,my,this.x,this.y);
if(d