Skip to content

Instantly share code, notes, and snippets.

@jcupitt
Created February 3, 2021 21:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jcupitt/0480501690f7019a69d41b0358384957 to your computer and use it in GitHub Desktop.
Save jcupitt/0480501690f7019a69d41b0358384957 to your computer and use it in GitHub Desktop.
bouncy balls
let numBalls = 13;
let spring = 1.01;
let balls = [];
function setup() {
createCanvas(720, 400);
for (let i = 0; i < numBalls; i++) {
balls[i] = new Ball(
random(width),
random(height),
random(30, 70),
i,
balls
);
}
noStroke();
fill(255, 204);
}
function draw() {
background(0);
balls.forEach(ball => {
ball.collide();
ball.move();
ball.display();
});
}
class Ball {
constructor(xin, yin, din, idin, oin) {
this.x = xin;
this.y = yin;
this.vx = 0;
this.vy = 0;
this.diameter = din;
this.id = idin;
this.others = oin;
}
collide() {
for (let i = this.id + 1; i < numBalls; i++) {
// console.log(others[i]);
let dx = this.others[i].x - this.x;
let dy = this.others[i].y - this.y;
let distance = sqrt(dx * dx + dy * dy);
let minDist = this.others[i].diameter / 2 + this.diameter / 2;
// console.log(distance);
//console.log(minDist);
if (distance < minDist) {
//console.log("2");
let angle = atan2(dy, dx);
let targetX = this.x + cos(angle) * minDist;
let targetY = this.y + sin(angle) * minDist;
let ax = (targetX - this.others[i].x) * spring;
let ay = (targetY - this.others[i].y) * spring;
this.vx -= ax;
this.vy -= ay;
this.others[i].vx += ax;
this.others[i].vy += ay;
}
}
}
move() {
this.x += this.vx;
this.y += this.vy;
if (this.x + this.diameter / 2 > width) {
this.x = width - this.diameter / 2;
this.vx *= -1;
} else if (this.x - this.diameter / 2 < 0) {
this.x = this.diameter / 2;
this.vx *= -1;
}
if (this.y + this.diameter / 2 > height) {
this.y = height - this.diameter / 2;
this.vy *= -1;
} else if (this.y - this.diameter / 2 < 0) {
this.y = this.diameter / 2;
this.vy *= -1;
}
}
display() {
ellipse(this.x, this.y, this.diameter, this.diameter);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment