xxxxxxxxxx
89
let bubble = [];
// let theBall;
function setup() {
createCanvas(400, 400);
for (let i = 0; i < 3; i++) {
let x = random(width);
let y = random(height);
let r = random(30, 50);
let xspeed = random(20, 1);
let yspeed = random(1, 10);
bubble[i] = new Bubble(x,y,r,xspeed,yspeed);
// theBall = new Bubble(400, 200, 30);
}
}
function draw() {
background(255);
// for (let i = 0; i < bubble.length; i++) {
// bubble[i].show();
// bubble[i].move();
// }
// theBall.x = mouseX;
// theBall.y = mouseY;
// theBall.show();
// theBall.move();
for (let b of bubble) {
b.show();
b.move();
let overlapping = false;
for (let other of bubble) {
if (b !== other && b.intersects(other)) {
overlapping = true;
}
}
if (overlapping) {
b.changeColor("blue");
} else {
b.changeColor("red");
}
}
}
class Bubble {
constructor(x, y, r, xspeed,yspeed) {
this.x = x;
this.y = y;
this.r = r;
this.xspeed=xspeed/10;
this.yspeed=yspeed/10;
this.color=0;
}
intersects(other) {
let d = dist(this.x, this.y, other.x, other.y);
return (d <= this.r + other.r)
}
changeColor(col) {
this.color = col;
}
contains(px, py) {
let d = dist(px, py, this, x, this.y);
if (d < this.r) {
return true;
} else {
return false;
}
}
show() {
stroke(255);
strokeWeight(4);
fill(this.color)
ellipse(this.x, this.y, this.r*2);
}
move() {
this.x+= this.xspeed;
this.y+= this.yspeed;
this.xspeed= this.bounce(this.x,0,width,this.xspeed);
this.yspeed= this.bounce(this.y,0,height,this.yspeed)
}
bounce(pos, min, max, speed) {
if (pos <= min || pos >= max) {
return speed *= -1;
}else return speed;
}
}