Circle Intersection
geometryfunctionjavascriptarchivedCircle collision test
A method for testing collision / intersection between two circles on a 2D surface is presented below in Javascript. Code in made as simple as possible to support adaptation to other languages.
function circlesIntersect(c1, c2)
{
return (c1.r + c2.r) >= (Math.abs(Math.sqrt(
((c1.x-c2.x) * (c1.x-c2.x)) +
((c1.y-c2.y) * (c1.y-c2.y)))));
}
Full example source code
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
var ctx = null, game = null;
var mouseX = -1, mouseY = -1;
var isOver = false;
var circle1 = { x:250, y:150, r:70 };
var circle2 = { x:150, y:250, r:40 };
window.onload = function() {
game = document.getElementById('game');
ctx = game.getContext('2d');
window.addEventListener('keypress', function(e) {
// Move second circle left, right, up, or down (respectively), depending on
// arrow key pressed, providing rectangle will not move outside of Canvas bounds
if(e.keyCode==37 && circle2.x>circle2.r) { circle2.x-= 5; }
else if(e.keyCode==39 && (circle2.x+circle2.r)<595) { circle2.x+= 5; }
if(e.keyCode==38 && circle2.y>circle2.r) { circle2.y-= 5; }
else if(e.keyCode==40 && (circle2.y+circle2.r)<395) { circle2.y+= 5; }
// Test if circles intersect (overlap)
isOver = circlesIntersect(circle1, circle2);
});
requestAnimationFrame(drawGame);
};
function circlesIntersect(c1, c2)
{
return (c1.r + c2.r) >= (Math.abs(Math.sqrt(
((c1.x-c2.x) * (c1.x-c2.x)) +
((c1.y-c2.y) * (c1.y-c2.y)))));
}
function drawGame()
{
if(ctx==null) { return; }
// Clear Canvas
ctx.fillStyle = "#ffffff";
ctx.fillRect(0, 0, 600, 400);
// Set fill and stroke colours depending on whether or not rectangle intersect
if(isOver)
{
ctx.fillStyle = "#ff9999";
ctx.strokeStyle = "#ff3333";
}
else
{
ctx.fillStyle = "#aaaacc";
ctx.strokeStyle = "#7777aa";
}
// Draw first (stationary) circle
ctx.beginPath();
ctx.arc(circle1.x, circle1.y, circle1.r, 0, 2*Math.PI);
ctx.closePath();
ctx.fill();
ctx.stroke();
// Draw second (user controlled) circle
ctx.beginPath();
ctx.arc(circle2.x, circle2.y, circle2.r, 0, 2*Math.PI);
ctx.closePath();
ctx.fill();
ctx.stroke();
// Ask browser for next frame...
requestAnimationFrame(drawGame);
}
</script>
</head>
<body>
<p>Move the smaller circle with the arrow keys. The colour of both circles will change when they intersect.</p>
<p>If you do not see any circles, check your browser supports Canvas elements, and has Javascript enabled.</p>
<canvas id="game" width="600" height="400"></canvas>
</body>
</html>