[英]Affecting one object in array p5.js - Javascript
Using p5 libraries, with p5 editor. 使用带有p5编辑器的p5库。
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. 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);
}
}
}
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. 您犯了一个小错误,但也花了我一段时间:P在glow
功能中,您设置了全局颜色,而不是单个气泡。
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. 因此,我建议按照以下方式调整您的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.