The solution is very easy when you define a ray with a point(= vector) and a direction vector, and the rectangle with a point(= vector) and two vectors representing the sides.
Suppose the ray is defined as R0 + t * D
, where R0
is the origin of the ray, D
is an unit vector representing its direction and t
is its length.
The rectangle can be represented with a corner point P0
, and two vectors S1
and S2
which should represent the sides (their length being equal to the length of the sides). You will need another vector N
normal to its surface, which is equal to the unit vector along the cross product of S1
and S2
.
Now, assume the ray intersects the rect at P
. Then, the direction of the ray, D
must make a nonzero angle with the normal N
. This can be verified by checking D.N < 0
.
To find the intersection point, assume P = R0 + a * D
(the point must be on the ray). You need to find the value of a
now. Find the vector P0P
. This must be perpendicular to N
, which means P0P.N = 0
which reduces to a = ((P0 - R0).N) / (D.N)
.
Now you need to check if the point is inside the rect or not. To do this, take projection Q1
of P0P
along S1
and Q2
of P0P
along S2
. The condition for the point being inside is then 0 <= length(Q1) <= length(S1)
and 0 <= length(Q2) <= length(S2)
.
This method is appropriate for any type of parallelograms, not only for rectangles.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…