If I have a vector inside a rectangle, how do I tell which side of the rectangle the vector will hit?

547 Views Asked by At

I'm trying to solve an issue where I basically have a vector inside of a rectangle. I want to figure out if the vector continues its trajectory, what side will it strike? The vector is given as an (x, y) pair showing velocity on the two planes. I also have its position within the larger square, and the size of the square.

How would I figure out something like this?

2

There are 2 best solutions below

0
On

Presumably you also have a starting position somewhere within the rectangle. Translate to put this point at the origin. If you compare the angle of the given vector to the angles of the rays from the origin out to the corners of the translated rectangle, you can easily tell which side will be hit. There’s no need to actually calculate these angles, either. You can use the slope of the rays together with some sign checks to narrow down the quadrant in which the collision will occur.

0
On

First you need equations of the sides of rectangle.
If you have points of it $A,B,C,D$ described by vectors, $r_{_A},r_{_B},r_{_C},r_{_D}$ where coordinates of $r_{_A}$ are $(x_{_A},y_{_A})$ etc.. you can write down 4 separate parametric equations for lines which are incidental to sides of rectangle

(1) $r_{_P}=(1-\lambda)r_{_A}+\lambda{r_{_B}}$
(2) $r_{_P}=(1-\lambda)r_{_B}+\lambda{r_{_C}}$
(3) $r_{_P}=(1-\lambda)r_{_C}+\lambda{r_{_D}}$
(4) $r_{_P}=(1-\lambda)r_{_D}+\lambda{r_{_A}}$ where $P$ lies on the line.

Now compose equation for your moving object from point $P_0$
(5) $r_{_P}= r_{_P0}+k{r{_u}}$
where $r{_u}$ is a unit vector in the direction of movement and $k$ some parameter.
Then solve 4 separate systems of equations for (1) and (5), (2) and (5), (3) and (5), (4) and (5) for unknown $k$ and $\lambda$.

System which gives solution $k>0$ and $\lambda\geq 0$ and $\lambda \leq 1$ is your proper solution for the given side of the rectangle. Weak probability but you can have two systems solved on conditions above. It means that you hit .. a vertex.