Collision of circles and rectangles

JavaScript Algorithm

Knowing how to handle collision between different objects of varying shapes, will come in handy if you are into game development or just enjoy solving algorithmic problems. In this post I discussed the conditions to determine the collision between circles, non-rotated rectangles and collision between rectangle and circle.

Circle-Circle collision

Two circles collide if the distance between them is less than the sum of their radii. i.e

circle-overlap
function hasCirclesCollided(c1, c2) {
  const d = Math.sqrt(Math.pow((c1.x - c2.x), 2) + Math.pow((c1.y - c2.y), 2));
  return d >= c1.r + c2.r
}

Rectangle-Circle collision

We find the closest point of the rectangle from the circle’s center. If the distance of this point from the center is less than the radius, then the two shapes collide. The nearest point is found by clamping circle’s center to rectangle’s coordinates.

circle-rectangle-overlap
function hasCircleRectangleCollided(c, r) {
  const nX = c.x - Math.max(r.x, Math.min(c.x, r.x + r.w))
  const nY = c.y - Math.max(r.y, Math.min(c.y, r.y+r.h));
  return nX * nX + nY * nY <= c.r * c.r
}

Note that the rectangle here must not also be rotated.

Rectangle-Rectangle collision

Rectangles collide if there is no gap between them and here the rectangles considered are non-rotating.

rectangle-overlap
function hasRectanglesCollided(r1, r2) {
    return r1.x < r2.x + r2.w &&
      r1.x + r1.w > r2.x &&
      r1.y < r2.y + r2.h &&
      r1.y + r1.h > r2.y
}