Ray-square intersection 3D

[亡魂溺海] 提交于 2020-08-25 06:51:33

问题


I know how to compute a ray-plane intersection, but how can I test if the intersection point is within a square on that plane? I was testing if the point was within a distance from the center of the square but I'm not sure if this is correct.


回答1:


Here is a method that works for any convex polygon: (see simplified version for squares at the end of answer)

Let p1,p2,p3,p4 denote the four vertices of your square and let q denote the intersection between the ray and the supporting plane. Let n denote a vector normal to the supporting plane (take for instance the cross-product (p2-p1) x (p3-p1)).

To determine whether q is in the square, compute the following four quantities:

o1=orient(q,p1,p2,n)
o2=orient(q,p2,p3,n)
o3=orient(q,p3,p4,n)
o4=orient(q,p4,p1,n)

where

orient(a,b,c,n) =  [(b-a) x (c-a)] . n
x: cross product; .: dot product

If o1,o2,o3 and o4 have all the same sign, then q is in the square (p1,p2,p3,p4)

It also works for any convex polygon (p1,p2,p3,p4,...,pn)

How does it work:

If you were in 2D, you would compute:

o1 = det(p1-q, p2-q)
o2 = det(p2-q, p3-q)
o3 = det(p3-q, p4-q)
o4 = det(p4-q, p1-q)

where det(v1,v2) = (x1*y2)-(x2*y1) denotes the determinant between two vectors.

In English, if o1,o2,o3,o4 have the same sign, for instance positive, this means that the angle (p1,q,p2) makes a "left turn". If all angles (p1,q,p2), (p2,q,p3), (p3,q,p4) and (p4,q,p1) are left turns, then q is inside the polygon. Whenever it is outside, there is a side (pi,pj) such that (pi,q,pj) makes a "right turn".

Now if we are in an arbitrary plane in 3D, there is no longer such a thing as "left turn" and "right turn", but we can introduce the normal vector n, and test whether (q-p1, q-p2, n) is a positively or negatively oriented 3D basis (this is what orient() computes).

Special case for squares

Compute

X = (q-p1).(p2-p1) / ||(p2-p1)||
Y = (q-p1).(p3-p1) / ||(p3-p1)||

If X >= 0 && X <= 1 && Y >= 0 && Y <= 1 then q is in the square (see Mbo's answer).




回答2:


Answer depends on how your square is defined.

If square is axis-aligned, it is enough to check that

(P.X >= Square.Left) and (P.X <= Square.Right) and 
(P.Y >= Square.Top) and (P.Y <= Square.Bottom)

If square is rotated, make projections of point onto two neighbor edges and check that they are in edge range.



来源:https://stackoverflow.com/questions/33685433/ray-square-intersection-3d

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!