xxxxxxxxxx
87
let circles = [];
let spin = false;
// circle class
class Circle {
constructor(x, y, size) {
this.x = x;
this.y = y;
this.size = size;
this.fill = color(random(255), random(255), random(255), 150);
this.speedX = random(-5, 5);
this.speedY = random(-5, 5);
this.angle = 0;
}
// display the circles
display() {
fill(this.fill);
ellipse(this.x, this.y, this.size, this.size);
}
// move the circles
move() {
// change the speed
this.x += this.speedX;
this.y += this.speedY;
// bounce the circles off the edges of the canvas
if (this.x + this.size / 2 >= width || this.x - this.size / 2 <= 0) {
this.speedX = -this.speedX;
}
if (this.y + this.size / 2 >= height || this.y - this.size / 2 <= 0) {
this.speedY = -this.speedY;
}
}
// spin the circles from the center
spinAround() {
// calculate center
let centerX = width / 2;
let centerY = height / 2;
this.angle += 0.05;
this.x =
centerX +
(this.x - centerX) * cos(this.angle) -
(this.y - centerY) * sin(this.angle);
this.y =
centerY +
(this.x - centerX) * sin(this.angle) +
(this.y - centerY) * cos(this.angle);
}
}
function setup() {
createCanvas(400, 400);
noStroke();
}
function draw() {
background(0);
for (let i = 0; i < circles.length; i++) {
circles[i].display();
if (spin) {
circles[i].spinAround();
}
if (keyIsPressed && key === " ") {
circles[i].move();
}
}
let size = random(10, 100);
let x = random(width);
let y = random(height);
// keep adding new circles but if array holds more than 100 circles start deleting
let circle = new Circle(x, y, size);
circles.push(circle);
if (circles.length > 100) {
circles.splice(0, 1);
}
}
// if mouse is pressed, spin the circles
function mousePressed() {
spin = !spin;
if (spin) {
for (let i = 0; i < circles.length; i++) {
circles[i].x = (width / circles.length) * i;
circles[i].y = height / 2;
}
}
}