How to check any point on polygon intersects with line?

54 Views Asked by At

I have input polygon, lets say I have x,y,width,height of rectangle on 2-d plane. I want to know does this ploygon intersects with a line ? What math I equations to use? I want to know, Red Rectangle intersects with blue line?

Solutions for Rectangle

Check each edge intersects with line, may be simple and basic solution. Is there any other way?

enter image description here

Pls add tags for this questions.

2

There are 2 best solutions below

3
On

I am merely stating the obvious:

If the edges of your rectangle are parallel to the $x$ and $y$ axis (as depicted in your graph), you can simplify the problem as follows. Suppose your line is of the form $y(x)=ax+b$.

If $a>0$, then it suffices to check whether $y$ intersects the left or lower edge of your rectangle.

If $a=0$, check whether it intersects the left edge.

If $a<0$, check whether it intersects the left or upper edge.

0
On

Here is one way of doing it in $\mathbb{R}^2$:

Suppose the line has the form $x_0 + t d \in \mathbb{R}^2$ for $t \in \mathbb{R}$. Let $p = (-d_2,d_1)$ ($p$ for 'perpendicular').

Given a point $x$, project $x$ onto the line $t p$, $t \in \mathbb{R}$ and compute the corresponding $t$, that is $t(x) = {p^T x \over \|p\|}$.

Now compute $t(c_k)$ for each corner $c_k$ and then we see that the line intersects the rectangle iff $\min t(c_k) \le t(x_0) $ and $\max t(c_k) \ge t(x_0) $.

(There is no need to divide by $\|p\|^2$ of course when doing the actual computation.)