xxxxxxxxxx
93
class Circle {
constructor() {
this.radius = random(6, 10);
this.diam = 2 * this.radius;
this.x = random(this.radius, width - this.radius);
this.y = random(this.radius, height - this.radius);
this.xVel = random(1, 2);
this.yVel = random(1, 2);
this.color = color(255);
this.alpha = 0;
}
checkBoundary() {
if (this.y > height - this.radius || this.y < this.radius) {
this.yVel *= -1;
this.alpha = 0;
}
if (this.x > width - this.radius || this.x < this.radius) {
this.xVel *= -1;
this.alpha = 0;
}
}
checkOverlap(otherCircle) {
// check if comparing to itself
if (this == otherCircle) {
return false;
}
// use distance between 2 circles and radius to check overlap
let cDist = dist(this.x, this.y, otherCircle.x, otherCircle.y);
return cDist < this.radius + otherCircle.radius;
}
checkAllOverlaps() {
let overlap = false;
for (let ci = 0; ci < circles.length; ci++) {
let aCircle = circles[ci];
if (this.checkOverlap(aCircle)) {
overlap = true;
}
}
if (overlap) {
this.color = color(255, 0, 0, this.alpha);
} else {
this.color = color(255, this.alpha);
}
}
update() {
this.y += this.yVel;
this.x += this.xVel;
this.alpha = min(255, this.alpha + 20);
this.checkBoundary();
this.checkAllOverlaps();
}
draw() {
fill(this.color);
stroke(0, this.alpha);
ellipse(this.x, this.y, this.diam, this.diam);
}
}
let circles = [];
let numCircles = 20;
function setup() {
createCanvas(400, 400);
for (let d = 0; d < numCircles; d += 1) {
let aCircle = new Circle();
circles.push(aCircle);
}
}
function draw() {
background(120);
// for each circle:
for (let d = 0; d < circles.length; d += 1) {
let aCircle = circles[d];
// draw
aCircle.draw();
// update and check boundary
aCircle.update();
}
}