Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 964
John Petterson Avatar asked Oct 18 '09 17:10

John Petterson


People also ask

What is the formula to find the point of intersection?

Point of intersection means the point at which two lines intersect. These two lines are represented by the equation a1x + b1y + c1= 0 and a2x + b2y + c2 = 0, respectively. Given figure illustrate the point of intersection of two lines.

Does line segment intersect rectangle?

Get the dot product of all 4 vertices (the corners of the rectangle) with the direction vector of the line segment. If all 4 have values of the same sign, then all the vertices lie on the same side of the line (not the line segment, but the infinite line) and thus the line does not intersect the rectangle.


1 Answers

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.

like image 187
Joren Avatar answered Sep 23 '22 10:09

Joren