Ben
Ben

Reputation: 16641

Intersection between ray and rectangle

In C++, in 2D, how can I find the point of intersection between a ray (defined by one point and a direction-vector) and a rectangle (defined by x, y, w, h)?

                   ________
                  |        |
                  |        |
------------------|        |
                  |________|

This is for a none frame based simulation, so I am not quite sure how to tackle the problem.

Upvotes: 2

Views: 3795

Answers (2)

MSalters
MSalters

Reputation: 179779

Your ray is defined by y=px+q. Defining your box as {R,B,L=R+w,T=B+h}, that means the right edge is intersected at y=pR+q; the left edge at y=pL+q, the bottom at x=(B-q)/p and the top at x=(T-q)/p.

To check that these intersections are with the line segments defining your box, you'll have to check that R <=x && x <= L and B <= y && y <= T respectively.

Upvotes: 2

Vyktor
Vyktor

Reputation: 20987

Rectangle in 2D = 4 line segments.

So your question actually is: How do I determine whether or not two lines intersect, and if they do, at what x,y point?

You calculate intersection for all line segments and than choose closes one based on |A-Xi|, where A is vector origin, Xi is intersect point and || represents length of vector (sqrt(A.x*Xi.x + A.y*Xi.y), you don't actually need to use sqrt() if you just need to compare distances and don't need exact number).

Upvotes: 5

Related Questions