Lesson 3 of 10

Rectangle collisions

Goal

A hits(a, b) function that doesn't count touching as a collision

01

Explanation

Most 2D games don't need exact shapes to detect collisions. Instead, they wrap each object in a rectangle whose sides are parallel to the axes, called an AABB, and ask one question that's quick to answer: do the two rectangles overlap?

Two rectangles overlap when they overlap on both axes at once. On the x axis that takes two conditions, a.x < b.x + b.w and a.x + a.w > b.x, which together mean each one starts before the other ends. The y axis needs the same two conditions. If they're apart on even one axis, they don't collide.

The comparisons here are strict on purpose, with no equality, because two rectangles that only touch along an edge do not count as colliding. The move function places the player flush against the edge of any wall it runs into. If touching counted as a collision, the player would still be "colliding" with that wall on the next frame, and as soon as it tried to slide along the wall it would get pushed through to the other side.

02

Your task

Write hits(a, b) for two rectangles shaped like { x, y, w, h }. It returns true if they overlap and false otherwise, and touching alone gives false. The move function is already written, and it relies on yours to stop the player at walls. To try it, click the preview and move the player with the arrow keys.

Checks

6 checks
  1. Overlapping rectangles collide
  2. Rectangles that are apart on either axis don't collide
  3. Touching along an edge isn't a collision
  4. A small rectangle inside a big one collides in either order
  5. move stops the player flush against the wall
  6. A player touching a wall can slide along it
03

Hints

0/3
Track lessons0 of 10 done

Build a real canvas game that runs in any browser, and learn the game loop, movement, collisions and scoring along the way.

Intermediate level, 10 lessons, 2.5 hours in total.

index.html
Preview
index.html100%
–/6

Press “Run and check” to grade your code.

6 checks listed under “Your task”.

Track lessons0 of 10 done

Build a real canvas game that runs in any browser, and learn the game loop, movement, collisions and scoring along the way.

Intermediate level, 10 lessons, 2.5 hours in total.