Lesson 8 of 10
Collision detection
- 13 min
- 6 checks
- 3 hints
- Go to task
Goal
Rectangles, circles and shapes that only touch
Explanation
Most games don't test collisions against a character's real shape but against a simple shape around it: either an axis-aligned bounding box (AABB), a rectangle whose sides are parallel to the axes, or a circle. That turns the test into just a few comparisons, cheap enough to run for thousands of entities every frame.
Two rectangles overlap when their extents overlap on x and on y at the same time, so if they're apart on just one axis, they don't overlap. Don't look for a corner of one inside the other: two rectangles that form a cross intersect without either one having a corner inside the other. Two circles overlap when the distance between their centers is less than the sum of their radii, and if you compare squared lengths, you don't need math.sqrt.
Watch the edges. If a wall starts exactly where the player ends, are they colliding? If you write <=, touching counts as a collision, so the player collides with the floor they're standing on every frame and gets stuck on the seam between two neighboring tiles. The rule here is clear: touching is not overlapping, and every comparison uses <, not <=.
Your task
Write aabbOverlap(a, b) for two rectangles shaped like { x, y, w, h }, where x, y is the top-left corner, and circlesOverlap(a, b) for two circles shaped like { x, y, r }. Both return true if the shapes overlap, and false if they touch or are apart.
Checks
6 checks- Two rectangles that partly overlap are detected
- Being apart on one axis is enough to rule out an overlap
- Two rectangles that form a cross overlap
- Touching at the edge is not overlapping
- Circles are measured by distance, not by axis
- Two circles that touch don't overlap