Code does not work (Bubble)

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

Answers

  • edited January 2017 Answer ✓

    @ line #37, you've forgotten to prefix property col w/ this: :-\"
    fill(col); -> fill(this.col);.

  • edited January 2017

    @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?

  • edited January 2017

    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.

  • edited January 2017
    • Just for curiosity's sake, there's an aspect of this bug which makes it harder to detect: :>
    • The fact that fill(col); works at 1st, displaying the randomly picked color for each Bubble instance.
    • The answer for that mystery is that col is accessed as a closure inside method display():
      https://developer.Mozilla.org/en-US/docs/Web/JavaScript/Closures
    • It also means there are 2 col now: constructor's 3rd parameter & the instance property this.col! @-)
    • Inside method clicked(), this.col is reassigned to another p5.Color object.
    • However display() keeps on using the closured parameter col w/ the originally passed p5.Color. ;;)
  • Thanks for your insights.

Sign In or Register to comment.