0

Check if two circles touch or intersect given center and radius

Function JavaScript 1 revisions 143 8 months ago 8 months ago
function doIntersect(c1, c2) {
    const distance = (c2.center.x - c1.center.x)**2 + (c2.center.y - c1.center.y)**2;
    return (c1.r - c2.r)**2 <= distance && distance <= (c1.r + c2.r)**2;
}

This is an efficient implementation that checks whether two circles, given their radiuses and centers touch/intersect or not.

For example, it returns true for all these types of circles:

Intersecting circles

While it returns false for:

Not intersecting circles

// These circles touch at (-1, 0)
const c1 = {r: 1, center: {x: 0, y: 0}};
const c2 = {r: 2, center: {x: 1, y: 1}};
doIntersect(c1, c2);                      // true