Unit 7 ยท JavaScript

7.10.4Object collider

A collider is the invisible shape used to detect whether two game objects touch. The simplest is the AABB (axis-aligned bounding box) rectangle test:

JavaScript
function collides(a, b) {
  return a.x < b.x + b.w &&     // a's left edge is left of b's right edge
         a.x + a.w > b.x &&     // a's right edge is right of b's left edge
         a.y < b.y + b.h &&     // a's top is above b's bottom
         a.y + a.h > b.y;       // a's bottom is below b's top
}
aboverlapa.xa.x + a.wb.xb.x + b.wAll four must be true:a.x < b.x + b.wa's left is left of b's righta.x + a.w > b.xa's right is right of b's lefta.y < b.y + b.ha's top is above b's bottoma.y + a.h > b.ya's bottom is below b's top
Two rectangles overlap only when they overlap on both the x axis and the y axis

For circles, compare the distance between centres with the sum of the radii:

JavaScript
function circleHit(a, b) {
  const dx = a.x - b.x, dy = a.y - b.y;
  return Math.sqrt(dx * dx + dy * dy) < a.r + b.r;
}

Tips: shrink the collider slightly smaller than the picture (a hitbox) so the game feels fair; draw the hitbox in a debug mode (ctx.strokeRect) while testing. For platform games, resolve collisions by moving the object back to the side it came from.