HTML and CSS Reference
In-Depth Information
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),
tx = ballA.x + Math.cos(angle) * min_dist,
ty = ballA.y + Math.sin(angle) * min_dist,
ax = (tx - ballB.x) * spring * 0.5,
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;
ball.vx *= bounce;
} 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(context);
}
(function drawFrame () {
window.requestAnimationFrame(drawFrame, canvas);
context.clearRect(0, 0, canvas.width, canvas.height);
balls.forEach(checkCollision);
balls.forEach(move);
balls.forEach(draw);
Search WWH ::




Custom Search