3

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

EmilioPelaez
  • 133
  • 6

2 Answers2

4

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)$.

Jason Zimba
  • 2,585
  • I am indeed writing code for this. This method was my first thought but it felt like brute force. From the lack of responses I'm guessing there's not a better/simpler way. Thanks for the input though, I'll mark your answer as correct. – EmilioPelaez Mar 19 '14 at 18:15
  • Ok thanks - and you're probably right that there are better answers. But also, "better" depends on the circumstances. This algorithm is slow and you wouldn't want to do this a million times inside of a loop.... But on the plus side, I had a working version of it on my computer in about 5minutes. Having done a tech startup, I learned to appreciate the virtues of "just getting the answer" and moving on to the next problem as quickly as possible. – Jason Zimba Mar 19 '14 at 18:59
0

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)$