Code

p5.js

Physics

Advanced Gravity, velocity accumulation, elastic wall bouncing, and ball-ball collision resolution — all implemented from first principles. Click to spawn more balls. p5.js Examples

const GRAVITY = 0.35;
const DAMPING  = 0.78;

// Each frame
b.vy += GRAVITY;       // accumulate gravity
b.x  += b.vx;
b.y  += b.vy;

// Wall bounce
if (b.y + b.r > p.height) {
  b.y   = p.height - b.r;
  b.vy *= -DAMPING;     // reverse + energy loss
  b.vx *= 0.98;         // friction
}

// Ball-ball collision
const dist = Math.sqrt(dx*dx + dy*dy);
if (dist < b.r + o.r) {
  const nx = dx / dist, ny = dy / dist;
  const overlap = (b.r + o.r) - dist;
  // separate overlapping balls
  b.x -= nx * overlap / 2;
  o.x += nx * overlap / 2;
  // exchange velocity along normal
  const relV = (b.vx - o.vx)*nx + (b.vy - o.vy)*ny;
  if (relV > 0) {
    b.vx -= relV * nx * DAMPING;
    o.vx += relV * nx * DAMPING;
  }
}