Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Points of intersection between line and rectangle

Tags:

math

Schematic

I have a given line R defined by an angle α. R goes through the origin of my plane. I also do have an rectangle, with known width and height. The rectangle has its bottom left corner on the origin.

A new line, parallel to R, is defined by a distance L from R (take A, B, and C as examples). I would like to find out the points where the new line intersects the rectangle (like P1 and P2 for the line A, P3 and P4 for B, and P5 and P6 for C).

What is the best way to find it?

like image 274
Vitor Py Avatar asked Aug 26 '10 14:08

Vitor Py


1 Answers

Use this page http://local.wasp.uwa.edu.au/~pbourke/geometry/lineline2d/

it gives formula for intersection of two lines. Intersect with every one of the 4 lines that make up rectangle separately, and then check that u_a (the place of intersection parametrized by a rectangle line) is between the correct bounds, to make sure that your line doesnt intersect it outside of the rectangle.

Note you'll need actual points not angles for this, but it is very easy to compute them. Line going through origin is simply (0,0)->(cos(a), sin(a))

Line x distance away from it, parallel is (0,0) + x*(sin(a),-cos(a)) -> (cos(a),sin(a)) + x*(sin(a),-cos(a))

because as you can notice, (sin(a), -cos(a)) is just a unit length vector that is perpendicular to your line, so you just add it on top of both points that form your original line.

like image 65
karpathy Avatar answered Oct 03 '22 15:10

karpathy