Ray/Rectangle intersection in 3D space

3.8k views Asked by At

Im having trouble with calculating whether line/ray intersects a rectangle (thats on a plane) in 3d space.

I have searched and the only thing I found was Ray and square/rectangle intersection in 3D but I just cant quite understand the last steps and how to apply it for my system.

So I have a Ray

struct Ray
{
  Vector3 m_startPoint;  // P0
  Vector3 m_direction;   // Direction Unit Vector
  float m_length;         // Ray length
};

and I have a quad defined by

struct Quad
{
    Vector3 p1;    
    Vector3 p2;
    Vector3 p3;
    Vector3 p4;
    Vector3 normal;
}

What I first did was calculate whether the ray would ever hit the plane using the dot product

float dotProd = D3DXVec3Dot(&ray.m_direction, &quad.normal);

if (dotProd < 0)     // if <0 ray will travel into the plane
{
    // Get the point of intersection
    float distToIntersection
    //Vector3D intersectPoint = ray.m_startPoint + (distToIntersection * ray.m_direction);

    // Check whether the point of intersection is within the bounds of the Quad
}

And this is where I get stuck...

I know its been answered before but I can't make it work for my system so would really appreciate some help.

2

There are 2 answers

2
Tommy On

Your existing dotProd test just tells you whether the direction of your ray is along the normal or away from it.

What you probably want to do is:

  1. get distance of start point and of end point from plane;
  2. if both distances have the same sign then stop — there's no intersection;
  3. otherwise calculate the intersection point — if start distance is s and end distance is e then it's necessarily at the point s / (s - e) along the line;
  4. perform a point-in-rectangle test on the point: if its x is in the x range of the box and its y is in the y range of the box then it's inside and the ray strikes the rectangle. Otherwise it does not.
0
Joseph O'Rourke On

"Could you show me the method of projecting onto 2D?"

Maybe this will help. Note the projection of a rectangle is a convex quadrilateral (not generally a rectangle), so you will need four LeftOf( ) tests to verify inclusion of the projected point.


          RectProjection
You can find LeftOf( ) in many place, including this textbook.

Don't forget to test if the rectangle lies in a plane orthogonal to the xy-plane, in which case you should project to either the xz- or the yz-plane.