createCanvas(1000, 1000);
let gridSize = int(sqrt(numBalls));
let spacing = width / gridSize;
for (let i = 0; i < gridSize; i++) {
for (let j = 0; j < gridSize; j++) {
let x = spacing / 2 + i * spacing;
let y = spacing / 2 + j * spacing;
balls[index] = new Ball(x, y);
for (let i = 0; i < balls.length; i++) {
this.r1 = random(50, 100);
this.b1 = random(50, 100);
this.g1 = random(50, 100);
this.ballVelocity = createVector(random(-2, 2), random(-2, 2));
this.ballLocation = createVector(x, y);
this.originalLocation = createVector(x, y);
this.repulsionForce = createVector(0, 0);
this.distanceFromMouse = 0;
fill(this.r1, this.g1, this.b1);
ellipse(this.ballLocation.x, this.ballLocation.y, this.d, this.d);
this.ballVelocity.limit(3);
this.ballLocation.add(this.ballVelocity);
this.moveToOriginalLocation();
if (this.ballLocation.x > width - this.d / 2 || this.ballLocation.x < this.d / 2) {
this.ballVelocity.x = -this.ballVelocity.x;
this.ballLocation.add(this.ballVelocity);
if (this.ballLocation.y > height - this.d / 2 || this.ballLocation.y < this.d / 2) {
this.ballVelocity.y = -this.ballVelocity.y;
this.ballLocation.add(this.ballVelocity);
let mousePos = createVector(mouseX, mouseY);
this.repulsionForce = p5.Vector.sub(this.ballLocation, mousePos);
this.distanceFromMouse = this.repulsionForce.mag();
if (this.distanceFromMouse < 150) {
this.repulsionForce.normalize();
this.repulsionForce.mult(map(this.distanceFromMouse, 0, 150, 8, 0));
this.ballVelocity.add(this.repulsionForce);
moveToOriginalLocation() {
if (this.distanceFromMouse >= 150) {
let attractionForce = p5.Vector.sub(this.originalLocation, this.ballLocation);
attractionForce.normalize();
attractionForce.mult(0.5);
this.ballVelocity.add(attractionForce);