簡體   English   中英

影響數組p5.js中的一個對象-Javascript

[英]Affecting one object in array p5.js - Javascript

使用帶有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);
        }
    }
}

您犯了一個小錯誤,但也花了我一段時間:P在glow功能中,您設置了全局顏色,而不是單個氣泡。

因此,我建議按照以下方式調整您的Bubble類:記住氣泡的顏色,然后在show所有氣泡時,根據是否單擊,以指定的顏色繪制氣泡。

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);
        }
    }
}

例子

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM