Please need help - p5.js - Problems with changing the color of the bubbles!

Hi everyone,

Could someone please help me? I am trying to change the color of the bubbles if the mouse is inside a bubble, but apparently it doesn’t work :frowning: I am not really sure what I have to change inside the “function events()”?!

Thanks a lot for your help and I wish u all a happy and healthy new year!

//obejcts_arrays_classes_mouseOver_interactions_changing color

let bubbles = [];

function setup() {
  createCanvas(400, 400);
  for (let i = 0; i < 12; i++) {
    let x = random(height);
    let y = random(width);
    let r = random(10, 40);
    let b = new Bubble(x, y, r);
    bubbles.push(b);
  }
}

function draw() {
  background(0);
  for (let i = 0; i < bubbles.length; i++) {
    bubbles[i].move();
    bubbles[i].display();
    bubbles[i].edge();
  }
}

function events() {
   for (let i = 0; i < bubbles.length; i++) {
      bubbles[i].over(mouseX, mouseY);   
    }
}

class Bubble {
  constructor(x, y, r) {
    this.x = x;
    this.y = y;
    this.r = r;
    this.brightness = 0; 
  }

  move() {
    this.x = this.x + random(-1, 1);
    this.y = this.y + random(-1, 1);
  }

  over(x, y) {
      let purpule = color(255, 115, 255);
      let d = dist(x, y, this.x, this.y);
      if (d < this.r) { 
          this.brightness = purpule;
      }else {
          this.brightness = 0;
      }
   }

  display() {
    stroke(255);
    strokeWeight(4);
    fill(this.brightness);
    ellipse(this.x, this.y, this.r, this.r);
  }

  edge () {
    if (this.x < 0 || this.y < 0) {
      this.x = 200;
      this.x += random(-5,5);
      this.y = 200;
      this.y += random(-5,5);
    }else if (this.x >= 400 || this.y >= 400) {
      this.x = 200;
      this.y = 200;
    }
  }
}


Hello there,

I do not see events being called anywhere… it should be called during the draw function.

Hope this helps

Hi Sky020,

It works :slight_smile:

Thanks a lot.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.