Search code examples
htmlalgorithmcanvascollision-detectionrectangles

Collision Detection rectangle/rectangle algorithm


http://jeffreythompson.org/collision-detection/rect-rect.php

I am trying to figure out the algorithm of the collision detection of the rectangle/rectangle with the rectangles' picture and code. According to Jeff Thompson's collision detection article, valuable r1RightEdge is r1x + r1w.

float r1RightEdge = r1x + r1w;
if (r1RightEdge >= r2x) {
// right edge of r1 is past left edge of r2
}

Is valuable r1RightEdge vertical dot line of the blue rectangle in the picture? If so, why is the valuable r1RightEdge is r1x +r1w instead of r1x+r1h?


Solution

  • Based on the example code

    if (r1x + r1w >= r2x &&     // r1 right edge past r2 left
      r1x <= r2x + r2w &&       // r1 left edge past r2 right
      r1y + r1h >= r2y &&       // r1 top edge past r2 bottom
      r1y <= r2y + r2h) {       // r1 bottom edge past r2 top
        return true;
    }
    return false;
    

    I under stand that x (in you case : r1x) mean horizontal position of the upper left dot of r1 - or R1LeftEdge, it only make sense if we add r1w (which is width) to it as they are both horizontal, the result is the horizontal upper right dot of r1 - or R1RightEdge. "r1x+r1h" doesn't make sense because one is horizontal and the other is vertical.