An example showing how to detect collision between two circles (uses HTML5/JS).
Two circles collide if the sum of their radii is greater than or equal to the distance between their centers.
function checkCircleCollision(c1, c2)
{
var a = c1.getX() - c2.getX();
var b = c1.getY() - c2.getY();
var c = (a * a) + (b * b);
var radii = c1.getRadius() + c2.getRadius();
return radii * radii >= c;
}
The distance between two points can be calculated using Pythagoras' theorem (c^2 = a^2 + b^2). In the example above, we are drawing the triangle so we can see the distance between the center of the circles (distance between two points).
We are also drawing each circle's radius (r1 and r2). Notice that when the circles are not colliding, the distance c is always greater than r1 + r2. When c = (r1 + r2)^2, the circles are touching each other by a single point. And when c < (r1 + r2)^2, the circles are colliding.
Instead of solving c = Math.sqrt(a^2 + b^2), we simply squared the radii variable.
You can find this slightly modified code in main.js as well as in KishiTechJS/circle.js.
In this example, we only detected if two circles are colliding. No response were implemented, other than changing the circle color.
From here, we should implement what happens with the circles as a response to the collision. Will they bounce? Explode? Disappear? This could be a topic for us to write about in the future and an exercise for you to practice!
We hope you enjoyed this article and let us know your thoughts about it! Reach us on Twitter and Facebook.
We also wrote a AABB-AABB collision detection article, which you can check out here.
Copyright © 2015-2016, Kishimoto Studios. All Rights Reserved.