简体   繁体   中英

Ray/rectangle intersection in JS

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:

例子

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!

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/(uv) , t1/(uv) 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM