3D中的射线与正方形/矩形相交

发布于 2021-01-29 16:20:12


正在制作游戏,并且仅在3D空间中寻找与正方形或矩形上的射线相交。搜索了网络,发现了许多解决方案,但是我无法理解的是在2D中有线和线段的交集脚本,但是我想不起来必须将其制作为3D。它从哪一侧与正方形或矩形相交并不重要,但它必须能够检索相交矢量的点,以便以后可以测试其在同一射线相交的其他相交之前或之后发生的距离。

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>;

}

关注者
0
被浏览
141
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

    在R3中为一条线创建一个矢量方程,然后求解该线在要对其进行测试的矩形平面中的交点。之后,测试该解决方案的点是否在界限之内就足够简单了。

    解的参数t可以通过以下方式找到:

    t = (a * (x0 - rx) + b * (y0 - ry) + c * (x0 - rz)) / (a * vx + b * vy + c * vz)
    

    哪里:

    a(x - x0) + b(y - y0) + c(z - z0) = 0
    

    是矩形所在平面的等式

    和:

    <x, y, z> = <rx + vx * t, ry + vy * t, rz + vz * t>
    

    是相关直线的向量方程。

    注意:

    <rx, ry, rz>
    

    是向量方程式的起始点,并且

    <vx, vy, vz>
    

    是上式的方向向量

    之后,将参数t插入向量方程式中即可为您测试距离。

    在此处输入图片说明



知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看