[WEB ANIMATION](https://www.kirupa.com/css_animations/index.htm) [BOOK](https://www.kirupa.com/book/animation_in_html_css_and_javascript.htm) [VIDEO](https://www.youtube.com/channel/UCZCQ3LXtU3IUzMBQBqN69KQ) # Collision Detection: Rectangles, Circles, and Points by [kirupa](https://www.kirupa.com/me/index.htm) | filed under [Web Animation](https://www.kirupa.com/html5/learn_animation.htm) **TL;DR:** Collision detection compares the numbers that describe two shapes. A point is inside a rectangle when it sits between both pairs of edges, two rectangles overlap when there's no gap on any side, and two circles overlap when their centers are closer than their radii added together. A circle touches a rectangle when the rectangle's closest point is inside it. - Comparing the squared distance with the squared radius gives the same answer as the real distance and skips the slower Math.sqrt call. - Clamping a circle's center to the rectangle's edges finds the rectangle's closest point, like the corner 57 pixels away that's just out of reach of a radius of 45. - After a hit, we push each ball half of the overlap away from the other and swap their speeds along the line between their centers so they bounce. - Checking only balls that share a grid cell cut 45 pair checks down to 6 for ten balls, a cheap broad phase before the real narrow-phase math. Whenever two things on our screen bump into each other, some code somewhere had to notice. A ball hits a paddle. A spaceship runs into an asteroid. Our mouse pointer lands on a shape we drew on a canvas. Each of those moments starts with the same question: are these two things touching right now? Answering that question quickly and correctly is known as **collision detection**, and it sounds a lot scarier than it actually is. Before we get into any of the details, here's a playground where we can drag rectangles, circles, and a point around. When two shapes overlap, both of them turn red: [Live demo: A collision detection playground where we can drag rectangles, circles, and a point around and watch them turn red when they overlap](https://www.kirupa.com/animations/examples/collision_playground.htm) In the following sections, we'll look at the small bit of math behind each of these checks, starting with a single point and working our way up to a circle touching a rectangle. After that, we'll look at what to do once two things collide, and how to keep everything fast when there are lots of objects flying around. Onwards! ## What Are We Actually Checking? When we draw shapes on a canvas, the browser doesn't keep track of them for us. Once a rectangle is painted, it's just a bunch of colored pixels. What we do have are the numbers we used to draw it. A rectangle is described by the position of its top-left corner and its size, and a circle is described by the position of its center and its radius: ```js const box = { x: 50, y: 40, width: 200, height: 120 }; const ball = { x: 150, y: 100, radius: 80 }; ``` Just like in CSS, `x` grows as we go right and `y` grows as we go *down*. A collision check is a function that takes the numbers for two shapes and returns `true` when they overlap and `false` when they don't. Every check in this article is a different way of comparing these numbers, so there's no pixel peeking involved. ## Is a Point Inside a Rectangle? The simplest check is figuring out whether a single point, like the spot where someone clicked, is inside a rectangle. Our rectangle's left edge is at its `x` value, and its right edge is at `x + width`. The top edge is at `y`, and the bottom edge is at `y + height`. A point is inside when it sits between the left and right edges *and* between the top and bottom edges: ![A rectangle whose left edge is at x = 50, right edge at x = 250, top edge at y = 40, and bottom edge at y = 160. The point (130, 90) is between both pairs of edges, so it's inside. The point (290, 100) has an x of 290, past the right edge at 250, so it's outside.](https://www.kirupa.com/animations/images/cd_point_rect.png) The point at (130, 90) is inside. Its x value of 130 is between 50 and 250, and its y value of 90 is between 40 and 160. The point at (290, 100) has a perfectly fine y value, but its x value of 290 is past the right edge at 250, so it's outside. One failed comparison is all it takes. Here's that check as code: ```js function pointInRect(px, py, rect) { return px >= rect.x && px <= rect.x + rect.width && py >= rect.y && py <= rect.y + rect.height; } ``` To use it with a mouse click, we need the click's position relative to the canvas instead of the whole page. Subtracting the canvas's own position takes care of that: ```js canvas.addEventListener("pointerdown", (event) => { const bounds = canvas.getBoundingClientRect(); const px = event.clientX - bounds.left; const py = event.clientY - bounds.top; if (pointInRect(px, py, box)) { console.log("You clicked the box!"); } }); ``` ## Is a Point Inside a Circle? Circles don't have edges we can line up against, so we need a different approach. Every point on a circle's edge is exactly one radius away from its center. That means a point is inside the circle when its distance from the center is less than or equal to the radius: ![A circle centered at (150, 100) with a radius of 80. One point is 50 pixels from the center, closer than the radius, so it's inside. Another point is 100 pixels away, farther than the radius, so it's outside.](https://www.kirupa.com/animations/images/cd_point_circle.png) To get that distance, we use the Pythagorean theorem. The horizontal gap between the two points is one side of a right triangle, the vertical gap is the other side, and the distance is the long side. For the green point at (190, 130), the gaps are 40 and 30, which works out to a distance of 50. That's less than the radius of 80, so it's inside. The red point at (230, 160) has gaps of 80 and 60 and sits 100 pixels away, so it's outside. If the triangle math is a bit fuzzy, [Measuring the Distance Between Two Points](https://www.kirupa.com/html5/using_the_pythagorean_theorem_to_measure_distance.htm) walks through it step by step. In code, there's one small trick: ```js function pointInCircle(px, py, circle) { const dx = px - circle.x; const dy = py - circle.y; return dx * dx + dy * dy <= circle.radius * circle.radius; } ``` We never call `Math.sqrt`. Instead of comparing the distance with the radius, we compare the *squared* distance with the *squared* radius. Both numbers are positive, so if one is bigger before squaring, it's still bigger after squaring, and the answer comes out the same. Skipping the square root doesn't matter much for one check, but it adds up when we're running thousands of them every frame. ## When Do Two Rectangles Overlap? Now for two shapes at once. The rectangles we've been drawing are never rotated. Their edges always run perfectly horizontal and vertical, lined up with the x and y axes. Rectangles like these are called **axis-aligned bounding boxes** (aka **AABBs**), and they're the workhorse of collision detection. Even when a game character has a complicated shape, it often gets an invisible box around it just for collision checks. Trying to list all the ways two rectangles can overlap gets messy fast. They can overlap at a corner, along a side, or one can sit completely inside the other. It turns out to be much easier to ask the opposite question: when are they *not* overlapping? Two rectangles miss each other only when there's a gap between them on one of four sides: ![Four small panels show rectangle B to the right of A, to the left, below, and above, each with a gap between them. Below them, A and B overlap with no gap on any side, so they collide, and the region they share is shaded.](https://www.kirupa.com/animations/images/cd_aabb.png) If B is entirely to the right of A, entirely to the left, entirely below, or entirely above, they can't be touching. If none of those four things are true, there's no gap anywhere, and the rectangles must overlap. Here's what that looks like in code: ```js function rectsOverlap(a, b) { return a.x < b.x + b.width && // A's left edge is left of B's right edge a.x + a.width > b.x && // A's right edge is right of B's left edge a.y < b.y + b.height && // A's top edge is above B's bottom edge a.y + a.height > b.y; // A's bottom edge is below B's top edge } ``` Each line rules out one of the four gaps. In the **Two rectangles** mode of the playground, the readout shows all four checks live as we drag, and the moment one of them fails, the red goes away. One small decision is hiding in there. Using `<` and `>` means two rectangles that only share an edge don't count as a collision. If we want touching to count, we can switch to `<=` and `>=`. Either choice is fine, as long as we pick one on purpose. This check isn't just for canvas drawings, either. The `getBoundingClientRect` method gives us the box of any HTML element on the page, with `x`, `y`, `width`, and `height` properties. That means `rectsOverlap` can also tell us whether a dragged card is over a drop zone. ## When Do Two Circles Overlap? Circles are even friendlier than rectangles. Imagine sliding two circles toward each other. They first touch at the exact moment the distance between their centers equals their two radii added together. Any closer than that, and they overlap: ![Three pairs of circles with radii 50 and 40, which add up to 90. When the centers are 120 apart, the circles miss. At 90 apart, they just touch. At 60 apart, they overlap.](https://www.kirupa.com/animations/images/cd_circles.png) Our circles have radii of 50 and 40, which add up to 90. When their centers are 120 apart, there's room to spare. At 90 apart, they're just kissing. At 60 apart, they overlap by 30 pixels. The code is our point-in-circle check with one change, where the radius becomes the sum of both radii: ```js function circlesOverlap(a, b) { const dx = b.x - a.x; const dy = b.y - a.y; const radii = a.radius + b.radius; return dx * dx + dy * dy <= radii * radii; } ``` We're comparing squared values again, so there's no square root here either. This is why so many games give their objects circular hitboxes. A circle check is one subtraction per axis, a couple of multiplications, and a single comparison, and it works the same no matter how the objects are turned. ## What About a Circle and a Rectangle? Mixing shapes is where things get a little more interesting. A ball bouncing toward a brick is a circle meeting a rectangle, and neither of our checks so far handles that. What we are going to do is find the one point on the rectangle that's closest to the circle's center. If that point is inside the circle, the shapes overlap. If even the closest point is outside the circle, every other point on the rectangle is farther away still, so they can't be touching: ![A rectangle with two circles near it, each with a radius of 45. For the circle to the upper left, the closest point on the rectangle is its top-left corner, 57 pixels from the circle's center, more than the radius, so they miss. For the circle on the right, the closest point is on the right edge, 30 pixels from its center, less than the radius, so they collide.](https://www.kirupa.com/animations/images/cd_circle_rect.png) Finding that closest point is easier than it sounds. We take the circle's center and **clamp** it to the rectangle, which means we squish each coordinate into the rectangle's range. If the center's x value is left of the rectangle, we use the left edge. If it's right of the rectangle, we use the right edge. Otherwise, we keep it as is. We do the same thing for y: ```js function clamp(value, min, max) { return Math.max(min, Math.min(value, max)); } function circleRectOverlap(circle, rect) { const closestX = clamp(circle.x, rect.x, rect.x + rect.width); const closestY = clamp(circle.y, rect.y, rect.y + rect.height); return pointInCircle(closestX, closestY, circle); } ``` For the circle up and to the left of the rectangle, both of its coordinates get clamped, so the closest point is the rectangle's top-left corner. That corner is 57 pixels away, which is more than the radius of 45, so they miss. For the circle on the right, only x gets clamped, so the closest point is on the right edge, just 30 pixels away. That's a hit. As a bonus, if the circle's center is inside the rectangle, nothing gets clamped at all. The closest point is the center itself, its distance is 0, and we correctly report a collision. In the **Circle + rectangle** mode of the playground, the white dot is this closest point. Drag the circle around a corner and watch the dot slide along the edges and then stick to the corner. ## What Do We Do When Two Things Collide? Detecting a collision is only half the job. Once we know two things are touching, we have to decide what happens next, which is called **collision response**. Sometimes the response is simple, like adding a point to a score or removing a coin. For things that move and bump into each other, the two most common responses are pushing the objects apart and making them bounce. If you've seen [Random Colors and a Bouncy Square](https://www.kirupa.com/animations/color_changing_bouncing_square.htm), you've already seen both of them with walls. When the square goes past a wall, we snap it back inside and flip its velocity. Two balls hitting each other work the same way, except that neither one is a wall, so they share the work: ![Before: two balls with a radius of 50 overlap by 12 pixels while moving toward each other. After: each ball moves 6 pixels away from the other along the line between their centers, so they just touch, and their velocities along that line are swapped so they head apart.](https://www.kirupa.com/animations/images/cd_separation.png) Objects move in little steps, so by the time we notice a collision, the two balls have usually sunk into each other a bit. In the figure, they overlap by 12 pixels. To separate them, we push each ball half of that overlap away from the other, along the line between their centers. After moving 6 pixels each, they're just touching. The bounce happens along that same line. Each ball's velocity has a part that points along the line between the centers and a part that doesn't. Only the part along the line changes. For two balls of the same weight, they simply trade those parts, a bit like the steel balls in a Newton's cradle. Here's the code for both steps: ```js function resolve(a, b) { const dx = b.x - a.x; const dy = b.y - a.y; const radii = a.radius + b.radius; const distanceSquared = dx * dx + dy * dy; if (distanceSquared > radii * radii) { return; // Not touching } // The direction from a's center toward b's center, with a length of 1 const distance = Math.sqrt(distanceSquared) || 0.0001; const nx = dx / distance; const ny = dy / distance; // 1. Push each ball half of the overlap away from the other const overlap = radii - distance; a.x -= nx * overlap / 2; a.y -= ny * overlap / 2; b.x += nx * overlap / 2; b.y += ny * overlap / 2; // 2. If they're heading toward each other, swap their speeds along that direction const closing = (a.vx - b.vx) * nx + (a.vy - b.vy) * ny; if (closing > 0) { a.vx -= closing * nx; a.vy -= closing * ny; b.vx += closing * nx; b.vy += closing * ny; } } ``` This time we do need the real distance, so `Math.sqrt` makes an appearance, but only after we know the balls are touching. The `closing` value tells us how fast the balls are moving toward each other along the line between them. If it's 0 or less, they're already heading apart, and bouncing them again would glue them together. Here are two dozen balls running this code on every frame. Try turning off **Push apart** and watch what happens when balls sink into each other: [Live demo: Two dozen balls bouncing off each other, with checkboxes to turn off pushing apart, turn off bouncing, and use a grid](https://www.kirupa.com/animations/examples/collision_response.htm) Without separating them, the balls visibly sink into each other when they collide, and they stay overlapped for a moment before they drift apart. With **Bounce** turned off as well, they pass right through each other like ghosts, flashing red as they go. If your device is set to reduce motion, the demo starts paused, so press **Play** to get it going. ## How Do We Check Lots of Objects Quickly? Each check we've written is fast. The problem is how many of them we need. With 10 balls, checking every ball against every other ball takes 45 checks. With the 24 balls in the demo, it's 276. With 1,000 balls, it's 499,500 checks, every single frame. The number of pairs grows roughly with the square of the number of objects, and that gets out of hand quickly. The fix is to split the work into two phases. The **broad phase** is a cheap, rough pass that throws out pairs that are obviously too far apart to touch. The **narrow phase** runs our real collision math, but only on the pairs that survive. A common broad phase is a grid. We divide the stage into cells, note which cells each object touches, and only compare objects that share a cell: ![The same 10 balls twice. On the left, every ball is checked against every other ball, which is 45 checks. On the right, the stage is split into a grid of cells, and only balls in the same cell get checked, which is just 6 checks.](https://www.kirupa.com/animations/images/cd_broad_phase.png) With the same 10 balls, the grid cuts our 45 checks down to just 6. Two balls on opposite sides of the stage never share a cell, so we never waste time on them. In the demo above, check **Use a grid** to see the same thing happen live. The cells with more than one ball light up, and the readout shows how few of the 276 pairs actually get checked. Grids work well when objects are roughly the same size and spread out. For other situations, there are fancier broad phase structures like quadtrees and sort-and-sweep. Physics libraries like Matter.js and Box2D use them under the hood, along with a lot of other tricks for rotated shapes and fast movement. Speaking of fast movement, there's one gotcha to keep in mind. Our checks only look at where things are on each frame, not where they were in between. A tiny bullet moving 50 pixels per frame can be on one side of a 20-pixel wall on one frame and on the other side on the next, and we'll never see them overlap. This is known as **tunneling**. Keeping speeds reasonable, using smaller time steps, or checking the path an object swept through are the usual ways around it. ## Conclusion Collision detection comes down to comparing a handful of numbers. A point is inside a rectangle when it's between both pairs of edges, and inside a circle when it's within one radius of the center. Two rectangles overlap when there's no gap on any side, two circles overlap when their centers are closer than their radii added together, and a circle touches a rectangle when the rectangle's closest point is inside the circle. Once we've detected a collision, pushing things apart and bouncing them turns a pile of overlapping shapes into something that feels solid, and a broad phase keeps it all fast when the shapes start to multiply. What we haven't covered are rotated rectangles and other odd shapes, which need a more involved technique called the separating axis theorem. The good news is that it's built on the same idea we used for rectangles: look for a gap, and if there isn't one, we have a collision. Before you go, here are a few things you can do: 1. Test your knowledge by taking the quiz below. 2. Read the next article in the series, [Morph Animation Without Morphing](https://www.kirupa.com/html5/creating_morph_animation_without_morphing.htm), or check out some related content: - [Measuring the Distance Between Two Points by using the Pythagorean Theorem](https://www.kirupa.com/html5/using_the_pythagorean_theorem_to_measure_distance.htm). Measure the distance between two points with a right triangle. - [Random Colors and a Bouncy Square](https://www.kirupa.com/animations/color_changing_bouncing_square.htm). Bounce a square off the walls and give it a new color each time. - [Moving Shapes on the Canvas Using the Keyboard](https://www.kirupa.com/canvas/moving_shapes_canvas_keyboard.htm). Move a shape around a canvas with the arrow keys. 3. Stuck on something, or curious about a detail we skipped? [Ask on the forums](https://forum.kirupa.com/), and we'll help you out. ## Test your knowledge! [Take the Collision detection Quiz](https://www.kirupa.com/quizzes/collision_detection.htm). Practice with 8 multiple-choice questions and an explanation after every answer.