xxxxxxxxxx
86
class Ball {
//create new ball using given arguments
constructor(pos, vel, radius, color) {
this.pos = pos;
this.vel = vel;
this.radius = radius;
this.color = color;
}
//collision detection
collide(check) {
if (check == this) {
return;
}
let relative = p5.Vector.sub(check.pos, this.pos);
let dist = relative.mag() - (this.radius + check.radius);
if (dist < 0) {
let mov = relative.copy().setMag(abs(dist/2));
this.pos.sub(mov);
check.pos.add(mov);
let otherNormal = relative.copy().normalize();
let approachSpeed = this.vel.dot(otherNormal) - check.vel.dot(otherNormal);
let approachVector = otherNormal.copy().setMag(approachSpeed);
this.vel.sub(approachVector);
check.vel.add(approachVector);
}
}
//give life to the ball
move() {
this.pos.add(this.vel);
if (this.pos.x < this.radius) {
this.pos.x = this.radius;
this.vel.x = -this.vel.x;
}
if (this.pos.x > width-this.radius) {
this.pos.x = width-this.radius;
this.vel.x = -this.vel.x;
}
if (this.pos.y < this.radius) {
this.pos.y = this.radius;
this.vel.y = -this.vel.y;
}
if (this.pos.y > height-this.radius) {
this.pos.y = height-this.radius;
this.vel.y = -this.vel.y;
}
}
//show the ball on the canvas
render() {
fill(this.color);
noStroke();
ellipse(this.pos.x, this.pos.y, this.radius*2);
}
}
let balls = []; //stores all the balls
function setup() {
createCanvas(window.windowWidth, window.windowHeight);
let n = 10;
//loop to create n balls
for (i = 0; i < n; i++) {
balls.push(new Ball(
createVector(random(width),random(height)),
p5.Vector.random2D().mult(random(5)),
random(20,50),
color(random(255),random(255),random(255))
));
}
}
function draw() {
background(0);
//loop to detect collision at all instances
for(let i = 0; i < balls.length; i++) {
for(let j = 0; j < i; j++) {
balls[i].collide(balls[j]);
}
}
//loop to render and move all balls
for(let i = 0; i < balls.length; i++) {
balls[i].move();
balls[i].render();
}
}