嘿嘿。正在制作游戏并仅在 3D 空间中寻找与正方形或矩形的光线相交。在网上搜索并找到了许多解决方案,但我无法理解 2D 中的线和线段交叉脚本,但我无法弄清楚必须将其设为 3D。 它从正方形或矩形的哪一侧相交并不重要,但它必须能够检索交点矢量,以便稍后可以测试到 se 的距离是否发生在同一射线交点上的其他交点之前或之后。
任何使用 python 或其他类似脚本语言的示例将不胜感激
编辑:不知道必须修改 2D 才能显示示例,但制作了一个新的并发布了两个。
//this is the exaple it test a ray onto a plane then look to se if that point is in the rectangle and saves it to test for distanse later
list Faces; //triangle faces
list Points; //
vector FindPoint(){
//calcute the point of intersection onto the plane and returns it
//if it can intersect
//else return ZERO_VECTOR
}
integer point-in-quadrilateral(){
//return 1 if the point is in the rectangular on the plane
//else return 0
}
default{
state_entry(){
integer n = (Faces != []); //return number of elements
integer x = 0;
while(x < n){
vector intersection = FindPoint( FromList(Faces, x) ); //take out a element and runs it trough the function
if(intersection != ZERO_VECTOR){
integer test = point-in-quadrilateral( FromList(Faces, x) ); //find out if the point is in rectangular
if(test == 1){ //if so
Points += intersection; //save the point
}
}
++x;
}
float first; //the distanse to the box intersection
integer l = (Points != []);
integer d;
while(d < l){
if(Dist( FromList(Points, d) ) < first) //if the new distanse is less then first
return 0; //then end script
++d;
}
}
}
//this is the 2D version
vector lineIntersection(vector one, vector two, vector three, vector four){
float bx = two.x - one.x;
float by = two.y - one.y;
float dx = four.x - three.x;
float dy = four.y - three.y;
float b_dot_d_perp = bx*dy - by*dx;
if(b_dot_d_perp == 0.0) {
return ZERO_VECTOR;
}
float cx = three.x-one.x;
float cy = three.y-one.y;
float t = (cx*dy - cy*dx) / b_dot_d_perp;
if(LineSeg){ //if true tests for line segment
if((t < 0.0) || (t > 1.0)){
return ZERO_VECTOR;
}
float u = (cx * by - cy * bx) / b_dot_d_perp;
if((u < 0.0) || (u > 1.0)) {
return ZERO_VECTOR;
}
}
return <one.x+t*bx, one.y+t*by, 0.0>;
最佳答案
当您定义一 strip 有点(= 向量)和方向向量的射线,以及带有一个点(= 向量)和两个表示边的向量的矩形时,解决方案非常简单。
假设射线定义为R0 + t * D
, 其中R0
是射线的原点,D
是表示其方向的单位向量,t
是它的长度。
矩形可以用角点表示P0
, 和两个向量 S1
和 S2
它应该代表边(它们的长度等于边的长度)。您将需要另一个矢量 N
垂直于其表面,等于沿 S1
叉积的单位向量和 S2
.
现在,假设射线与矩形相交于 P
.然后,光线的方向,D
必须与法线成非零角 N
.这可以通过检查 D.N < 0
来验证.
要找到交点,假设 P = R0 + a * D
(点必须在射线上)。您需要找到 a
的值现在。找到向量 P0P
.这必须垂直于 N
, 这意味着 P0P.N = 0
减少到 a = ((P0 - R0).N) / (D.N)
.
现在您需要检查点是否在矩形内。为此,采用投影 Q1
的 P0P
沿S1
和 Q2
的 P0P
沿S2
.点在里面的条件是0 <= length(Q1) <= length(S1)
和 0 <= length(Q2) <= length(S2)
.
此方法适用于任何类型的平行四边形,不仅适用于矩形。 [更新:看起来这个关于平行四边形的陈述造成了一些混淆。在平行四边形(也包括矩形)的情况下,一侧的投影应沿另一侧进行,而不仅仅是垂直线(引用最后一段:“沿 Q1
投影 P0P
S1
和 Q2
的 P0P
沿着 S2
”)。这就像在轴彼此不垂直的坐标系中工作。]
关于python - 3D 中的射线和正方形/矩形相交,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8812073/