xxxxxxxxxx
98
class Ball {
constructor(pos, vel, radius, color) {
// Creating a new Ball Object
this.pos = pos;
this.vel = vel;
this.radius = radius;
this.color = color;
}
isColliding(check) {
// Possibility of Collision between two balls
if (check == this) {
// Ball at check is itself
return;
}
let centerDist = p5.Vector.sub(check.pos, this.pos); // Distance between centers of two balls
let dist = centerDist.mag() - (this.radius + check.radius); // Distance between edges of two balls
return dist <= 0;
}
collide(check) {
// Reversing Velocity on Collision
if (this.isColliding(check)) {
this.vel.mult(-1);
check.vel.mult(-1);
}
}
move() {
// Moving the Ball
this.pos.add(this.vel); // Move at its velocity
// Wall Collision
if (this.pos.x > width - this.radius || this.pos.x < this.radius) {
// Left and Right Walls
this.vel.x = -this.vel.x;
}
if (this.pos.y > height - this.radius || this.pos.y < this.radius) {
// Top and Bottome Walls
this.vel.y = -this.vel.y;
}
}
//show the ball on the canvas
render() {
fill(this.color, 100, 100); // Set color of ball
noStroke();
ellipse(this.pos.x, this.pos.y, this.radius * 2); // Draw the ball
}
}
let balls = []; // Stores all the balls
function setup() {
createCanvas(window.windowWidth, window.windowHeight);
let n = 10;
colorMode(HSB);
while (balls.length != n) {
// While Loop to create n balls
let newBall = new Ball(
createVector(random(40, width - 40), random(40, height - 40)),
p5.Vector.random2D().mult(random(5)),
random(20, 40),
random(0, 360)
);
let isOkay = true; // Any point is valid discovered otherwise
for (let j = 0; j < balls.length; j++) {
if (newBall.isColliding(balls[j])) {
// Checking for its validity
isOkay = false;
break;
}
}
if (isOkay) {
// Pushing all valid balls
balls.push(newBall);
}
}
}
function draw() {
background("black");
for (let i = 0; i < balls.length; i++) {
// Loop to detect Collision
for (let j = 0; j < i; j++) {
balls[i].collide(balls[j]);
}
}
for (let i = 0; i < balls.length; i++) {
// Loop to move and render balls
balls[i].move();
balls[i].render();
}
}