Skip to content

Instantly share code, notes, and snippets.

@simudream
Created November 27, 2014 00:38
Show Gist options
  • Save simudream/8f0fc214555b661ae7ce to your computer and use it in GitHub Desktop.
Save simudream/8f0fc214555b661ae7ce to your computer and use it in GitHub Desktop.
QwbNKd
<canvas id="canvas"></canvas>
(function() {
"use strict";
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
var balls = [];
var numBalls = 10;
var bounce = -0.5;
var spring = 0.03;
var gravity = 0.1;
function Ball(radius, color) {
this.x = 0;
this.y = 0;
this.color = color || 'red';
this.radius = radius || 40;
this.vx = 0;
this.vy = 0;
}
Ball.prototype.draw = function () {
ctx.beginPath();
ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2);
ctx.fillStyle = this.color;
ctx.fill();
};
for (var i = 0; i < numBalls; i++) {
var ball = new Ball(Math.random() * 30 + 20, 'hsla(' + Math.random() * 360 + ', 100%, 50%, 1)');
ball.x = Math.random() * canvas.width / 2;
ball.y = Math.random() * canvas.height / 2;
ball.vx = Math.random() * 6 - 3;
ball.vy = Math.random() * 6 - 3;
balls.push(ball);
}
function checkCollision(ballA, i) {
for (var ballB, dx, dy, dist, min_dist, j = i + 1; j < numBalls; j++) {
ballB = balls[j];
dx = ballB.x - ballA.x;
dy = ballB.y - ballA.y;
dist = Math.sqrt(dx * dx + dy * dy);
min_dist = ballA.radius + ballB.radius;
if (dist < min_dist) {
var angle = Math.atan2(dy, dx);
var tx = ballA.x + Math.cos(angle) * min_dist;
var ty = ballA.y + Math.sin(angle) * min_dist;
var ax = (tx - ballB.x) * spring * 0.5;
var ay = (ty - ballB.y) * spring * 0.5;
ballA.vx -= ax;
ballA.vy -= ay;
ballB.vx += ax;
ballB.vy += ay;
}
}
}
function move(ball) {
ball.vy += gravity;
ball.x += ball.vx;
ball.y += ball.vy;
if (ball.x + ball.radius > canvas.width) {
ball.x = canvas.width - ball.radius;
}
else if (ball.x - ball.radius < 0) {
ball.x = ball.radius;
ball.vx *= bounce;
}
if (ball.y + ball.radius > canvas.height) {
ball.y = canvas.height - ball.radius;
ball.vy *= bounce;
}
else if (ball.y - ball.radius < 0) {
ball.y = ball.radius;
ball.vy *= bounce;
}
}
function draw(ball) {
ball.draw();
}
(function loop() {
requestAnimationFrame(loop);
ctx.clearRect(0, 0, canvas.width, canvas.height);
balls.forEach(checkCollision);
balls.forEach(move);
balls.forEach(draw);
}());
}());
body, canvas {
margin: 0;
padding: 0;
display: block;
background: black;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment