views:

2023

answers:

5

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?

PS: I'm working with C# but a solution in a similar language would be fine.

Thanks

A: 

I'll not give you a program to do that, but here is how you can do it:

  • calculate the angle of the line
  • calculate the angle of a line from the center of the rectangle to one of it's corners
  • based on the angles determine on which side does the line intersect the rectangle
  • calculate intersection between the side of the rectangle and the line
Lukáš Lalinský
+1  A: 

You need to find the endpoints of the line in the rectangle that intersects your line. If you have those, you can derive the equation of that line and then determine your intersection point as shown here: http://id.mind.net/~zona/mmts/intersections/intersectionOfTwoLines1/intersectionOfTwoLines1.html

The endpoints of the top line of your rectangle (assuming the rectangle is level) are:

point A: 
    x = B - width/2
    y = B + height/2

point B:
    x = B + width/2
    y = B + height/2
Robert Harvey
A: 

I don't know if this is the best way, but what you could do is to figure out the proportion of the line that is inside the rectangle. You can get that from the width of the rectangle and the difference between the x coordinates of A and B (or height and y coordinates; based on the width and height you can check which case applies, and the other case will be on the extension of a side of the rectangle). When you have this, just take that proportion of the vector from B to A and you have your intersection point's coordinates.

jk
+2  A: 

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

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.
Joren
+3  A: 

You might want to check out Graphics Gems (http://tog.acm.org/resources/GraphicsGems/gemsii/xlines.c) - this is a classic set of routines for graphics and includes many of the algorithms required. Although it's in C and slightly dated the algorithms still sparkle and it should be trivial to transfer to other languages.

For your current problem the just create the four lines for the rectangle and see which intersect your given line.

peter.murray.rust