4
votes

I am really not able to create a "point" (straight with an angle starting at a specific point) rectangle intersection to find the intersecting points (using JS). Just found out it's called "ray", so I edited the title.

I read so much about it and found many solutions for line/line intersections and line/rectangle intersections etc.

In my case, I don't have a line with start and endpoint, but a point with a given angle from which there needs to be a line till the intersection point.

Later on, the line should only be visible in the inner auf the rectangle, that's why I need the intersection. The rectangle is always axis-aligned.

I have no idea how to get that intersection because of the many cases (point in rectangle, point out of the rectangle, negative values). And I never worked with vectors.

I created an image to make it clearer:

Example

Any ideas on how to get the intersection points?

Probably I have to start testing every line of the rectangle against my straight line. But I even don't know how to check that...

Thank you so much for your help!

1
I have to rush off, so I can only point you the right way: Sine, cosine, and triangles. Here's what the triangles look like: i.stack.imgur.com/clv7Q.jpg - T.J. Crowder
Quick question based on your image: are the rectangles always axis aligned? - Michael Beeson
More about sine and cosine and how they relate to this: mathsisfun.com/sine-cosine-tangent.html - T.J. Crowder
@MichaelBeeson Yes, the rectangle is always axis aligned! - Timo
As you're basicly working with lines (rectangle is four separate lines), you can create equations for the lines (y = kx + b) using trigonometric functions, then an intersection occurs at Rect(x) - Line(x) === 0. - Teemu

1 Answers

1
votes
An algebraic solution:

Assume the window to be [0, W]x[0, H]. We write the equation of the half line as

X = x + t.u
Y = y + t.v

where t ≥ 0.

Let us assume u, v ≥ 0 for now. We want to solve the inequations

0 ≤ t
0 ≤ x + t.u ≤ W
0 ≤ y + t.v ≤ H

or

    0 ≤ t.u.v
- x.v ≤ t.u.v ≤ (W - x).v
- y.u ≤ t.u.v ≤ (H - y).u

There is a solution iff

t0 < t1

where

t0= max(0, - x.v, - y.u)
t1= min((W - x).v, (H - y).u).

The intersection points are obtained by plugging the values of t0/(u.v), t1/(u.v) in the equation of the half-line.

You have to repeat that discussion for all signs of u, v, including 0. There are 9 combinations, but this is manageable.