Week 6

Bubble Bath

I applied Bouncing Ball using Array example to this project. I planned to create bubbles that can interact with the mouse hover action.

Creating Class:

 class Bubble {
  constructor(x, y) {
    this.x = x;
    this.y = y;
    this.xdir = random(-1, 1);
    this.ydir = random(-2, -0.5); //elevates
    this.size = random(5, 50);
  }

I added random features. When ydir has a random value between -2 and -0.5, it gets closer to 0, which means the bubble moves upward from the bottom.

  move() {
    this.x += this.xdir;
    this.y += this.ydir;
    

    // Wind
    let d = dist(this.x, this.y, mouseX, mouseY);
    if (d < 60) {
      this.x += (this.x - mouseX) *0.06;
      this.y += (this.y - mouseY) *0.06;
    }
  }

The values of this.x and this.y follow the position changes based on xdir and ydir. Then I used the dist() function to create an interactive effect. This code measures the distance between each bubble’s position (xy) and the mouse position (mouseXmouseY). When the mouse moves within 60px of a bubble, the bubble’s position changes.

Because I’m subtracting this.x by mouseX, the bubble moves in the opposite direction from the mouse. At first, I only tried this.x += (this.x - mouseX); but the movement was too sudden, so I multiplied it by 0.06 to make the motion smoother.

Array:

 let bubbles = [];

 function setup() {
  createCanvas(400, 600);
}

 function draw() {
  background(220, 255, 255);

  // new bubble
  if (frameCount % 3 == 0) {
    bubbles.push(new Bubble(random(width), height));
  }

  for (let i = 0; i < bubbles.length; i++) {
    let b = bubbles[i];
    b.move();
    b.display();
  }
}

I applied an array function to create infinite bubble motion.
First, I used the modulus operator to control the timing of creating new bubbles.
By dividing frameCount by 3 and checking if the result is 0, new bubbles are generated every time when frameCount is a multiple of 3.

Then, I used bubbles.push() to create new bubble objects. Each bubble appears at a random x position, and its y position is set to height, so it starts at the bottom of the canvas.
0 = top of the canvas/ height = bottom of the canvas

Finally, I used a for loop to go through the array and continuously update and display each bubble on the screen, creating an infinite motion.