Circle Collision
HTML
<!DOCTYPE html>
<body>
<script>
var context;
var xcords = [];
var ycords = [];
var xdirs = [];
var ydirs = [];
var circles;
//fill variables
circles = getRandomInt(2, 15);
for (i = 0; i < circles; i++) {
xcords[i] = getRandomInt(0, 1920);
ycords[i] = getRandomInt(0, 900);
xdirs[i] = getRandomInt(2, 7);
ydirs[i] = getRandomInt(2, 7);
}
function init() {
context = canvas.getContext('2d');
setInterval(draw, 10);
}
function collides(x, y) {
if (Math.hypot(xcords[y] - xcords[x], ycords[y] - ycords[x]) < 50) {
return true;
} else return false;
}
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
function draw() {
context.clearRect(0, 0, 1920, 900);
//make some circles
for (i = 0; i < circles; i++) {
context.beginPath();
context.fillStyle = "#ff0000";
context.arc(xcords[i], ycords[i], 20, 0, Math.PI * 2, true);
context.closePath();
context.fill();
}
//boundaries
for (i = 0; i < circles; i++) {
if (xcords[i] < 0 || xcords[i] > 1920) xdirs[i] *= -1;
if (ycords[i] < 0 || ycords[i] > 900) ydirs[i] *= -1;
}
//collision
/*if(collides(xcords[0], xcords[1]));
{
xdirs[0] *= -1;
xdirs[1] *= -1;
ydirs[0] *= -1;
ydirs[1] *= -1;
}*/
for (i = 0; i < circles; i++) {
for (j = 0; j < circles; j++) {
if (collides(xcords[i], xcords[j]) < 50) {
xdirs[i] *= -1;
xdirs[j] *= -1;
ydirs[i] *= -1;
ydirs[j] *= -1;
}
}
}
//collision
/*
if(Math.hypot(x2-x, y2-y) < 50)
{
dy = -dy;
dx = -dx;
dx2 = -dx2;
dy2 = -dy2;
}
*/
//movement
for (i = 0; i < circles; i++) {
xcords[i] +=...