We are about to switch to a new forum software. Until then we have removed the registration on this forum.
What I want to do is I want to make 4 ellipse on the screen and then I want to change their color by clicking over them. My following code only draws circles but does not change their color. What I am missing I do not understand. Any comment ?
var bubbles = [];
function setup() {
createCanvas(600, 300);
for (var i = 0; i < 4; i++){
x = random(width);
y = random(height);
var col = color(random(0, 255), 0, random(0, 255));
bubbles.push(new Bubble(x, y, col));
}
}
function mousePressed(){
for(var i = 0; i < bubbles.length; i++){
bubbles[i].clicked();
}
}
function draw() {
background(0);
// Here displaying bubbles on the screen
for(var i = 0; i < bubbles.length; i++){
bubbles[i].display();
}
}
// constructor
function Bubble(x, y, col){
this.x = x;
this.y = y;
this.col = col;
this.display = function(){
stroke(255);
fill(col);
ellipse(this.x, this.y, 40, 40);
}
this.clicked = function(){
var d = dist(mouseX, mouseY, this.x, this.y);
if (d < 20){
this.col = color(0, 255, 0);
}
}
}
Answers
@ line #37, you've forgotten to prefix property col w/
this
: :-\"fill(col);
->fill(this.col);
.@GoToLoop : Oh... thank you so much. You don't know that I have spent more than half an hour figuring out what the error is.
How did you figure out that just by looking at the code snippet or p5.js helped you with that?
I confess I've just copied and pasted your code here: ;))
https://OpenProcessing.org/sketch/create
I make that same error many times too! B/c I'm used to Java.
And for most cases, we don't need to prefix fields w/
this
in Java. ~O)You are right. Thanks once again for the help.
fill(col);
works at 1st, displaying the randomly picked color for each Bubble instance.https://developer.Mozilla.org/en-US/docs/Web/JavaScript/Closures
Thanks for your insights.