How to find the intersection point between a line and a rectangle?

John Petterson picture John Petterson · Oct 18, 2009 · Viewed 61.4k times · Source

I have a line that goes from points A to B; I have (x,y) of both points. I also have a rectangle that's centered at B and the width and height of the rectangle.

I need to find the point in the line that intersects the rectangle. Is there a formula that gives me the (x,y) of that point?

Answer

Joren picture Joren · Oct 18, 2009

The point A is always outside of the rectangle and the point B is always at the center of the rectangle

Assuming the rectangle is axis-aligned, this makes things pretty simple:

The slope of the line is s = (Ay - By)/(Ax - Bx).

  • If -h/2 <= s * w/2 <= h/2 then the line intersects:
    • The right edge if Ax > Bx
    • The left edge if Ax < Bx.
  • If -w/2 <= (h/2)/s <= w/2 then the line intersects:
    • The top edge if Ay > By
    • The bottom edge if Ay < By.

Once you know the edge it intersects you know one coordinate: x = Bx ± w/2 or y = By ± h/2 depending on which edge you hit. The other coordinate is given by y = By + s * w/2 or x = Bx + (h/2)/s.