[Math] Find collision point between vector and fencing rectangle

trigonometry

it has been a few years since I left University, I have been unsuccessfully trying to solve this problem for a while now, I thought I might give StackExchange a try. (I'm making a game)

Given a cartesian area, the following information is known (please refer to chart)

  • I know point of origin of a vector (x,y) and its angle
  • Said vector is fenced by a rectangle, for which I know width/height (bottom left at 0,0)

I would like to know what the collision point (x,y) between the vector and the fencing rectangle

Any help/pointer would be greatly appreciated.

PS: The angle and point of origin of the vector will change so ideally the solution would work with any angle/point of origin

Thanks

enter image description here

Best Answer

Let $a = \cos(\theta)$ and $b = \sin(\theta)$, where $\theta$ is the angle from the $x$-axis to the angle of your ray. Now solve the four equations $$ x + a t_1 = width \\ y + b t_2 = height \\ x + a t_3 = 0 \\ y + b t_4 = 0 $$ by computing (assuming a and b are different from zero) : $$ t_1 = (width - x) / a \\ t_2 = (height - y) / b\\ t_3 = -x/a \\ t_4 = -y / b $$

Among all the numbers $t_1, \ldots, t_4$, compute the smallest nonnegative one, and call that $t$. So it $t_1 = 4, t_2 = -2, t_3 = 3, t_4 = 9$, then $t = 3$. If all four are negative numbers (which can happen only if $(x, y)$ is outside the rectangle), then there's no intersection.

Assuming there is at least one non-negative $t_i$, the intersection point is at $(x + ta, y + tb)$.

Related Question