Rectangle intersection with a Rectangle

Algorithm

For each line segment that your rectangle could be intersecting with, do the following:

  1. For each corner of your rectangle, check if the distance from that point to the line is less than some epsilon, where epsilon is a reasonable small number (usually a 1 or 2 units, depending on the size of your lines).
  2. To check each point, use the "distance from point to line segment" formula, which can be found here (I will not derive it just yet)
  3. If a collision is found, we have all of the information required to solve the collision:
    • Collision Normal: This is the perpendicular to the line segment, which can be found by:
      Vector2 getNormalToLineSegment(LineSegment* segment) {
          Vector2 direction = segment->end - segment->start;
          return *Vector2 { -direction.y, direction.x }).normalize();
      }
      				
    • First Point of Application: Get the vector from the center of the rectangle (most like your position) to the corner which intersected.
    • Second Point of Application: Get vector from center of line to the corner which intersected.

Live Example