Find intersection of line segment in rectangle perimeter.

1.4k Views Asked by At

I want to find the best way to calculate the point in the perimeter of a rectangle in which a line segment intersects.

p is a point inside the rectangle ($(0, 0)$ is in the center of the rectangle).

$\theta$ is the angle of the of the line segment and it can go from $0$ to $2\pi$.

Thanks in advance.

My Problem

2

There are 2 best solutions below

2
On BEST ANSWER

This is not an analytic solution, but I quickly wrote a computer program as follows. (I thought you might be writing code for this.)

Given the initial point $(x_0, y_0)$ and the direction $\theta$, the solution is immediate if $\theta = 0$, $\pi/2$, $\pi$, or $3\pi/2$. So assume $\theta$ is none of these values and compute the four numbers

$$t_1 = (w/2 - x_0)/\cos\theta$$ $$t_2 = (-w/2 - x_0)/\cos\theta$$ $$t_3 = (h/2 - y_0)/\sin\theta$$ $$t_4 = (-h/2 - y_0)/\sin\theta$$

Let $t^\star$ be the smallest positive value among these. Then the intersection point is $(x_0 + t^\star\cos\theta, y_0+t^\star\sin\theta)$.

0
On

Hint: Let $h$ be the length of the hypotenuse, and let $l$ be the length of the side that runs along the height (basically the side going vertically). Then $\sin(\theta)=\dfrac{l}{h}$. So $l=h\sin(\theta)$