I try to implement ray-box intersection algorithm given by the following code. However, I'm not really understand for two cases as shown in the following figures. Firstly, when the box is located in front of the ray, why the code give intersection even though the end point of the ray doesn't intersect with the box. A similar observation can be seen from the second case when the ray origin is located inside the box. Is this nature of the algorithm? How can solve this problem?

Fig.1: Case 1

Fig.2: Case 2

// r.dir is unit direction vector of ray
dirfrac.x = 1.0f / r.dir.x;
dirfrac.y = 1.0f / r.dir.y;

// lb is the corner of AABB with minimal coordinates - left bottom, rt is maximal corner
// r.org is origin of ray
float t1 = (lb.x - r.org.x)*dirfrac.x;
float t2 = (rt.x - r.org.x)*dirfrac.x;
float t3 = (lb.y - r.org.y)*dirfrac.y;
float t4 = (rt.y - r.org.y)*dirfrac.y;

float tmin = max(max(min(t1, t2), min(t3, t4)));
float tmax = min(min(max(t1, t2), max(t3, t4)));

// if tmax < 0, ray (line) is intersecting AABB, but the whole AABB is behind us
if (tmax < 0)
    t = tmax;
    return false;

// if tmin > tmax, ray doesn't intersect AABB
if (tmin > tmax)
    t = tmax;
    return false;

// if tmin < 0 then the ray origin is inside of the AABB and tmin is behind the start of the ray so tmax is the first intersection
if(tmin < 0) {
  t = tmax;
} else {
  t = tmin;
return true;
  • 3
    \$\begingroup\$ The ray is infinite, the start and end point are only there to define it \$\endgroup\$
    – Bálint
    Jul 4 '18 at 10:08
  • \$\begingroup\$ @Bálint that looks like an answer to me. If you add in a method to check whether the intersection is within a desired max length/depth then I'd say it would be a very good answer. :) \$\endgroup\$
    – DMGregory
    Jul 4 '18 at 11:42

Rays are infinite, the start and endpoint only define them. What you're looking for is a line segment based intersection.

It's very easy to convert a ray-box intersection to a line segment-box one since we know the point has to lie on the line that goes through the ray, we only need to check whether the bounding box of the line segment contains it. So convert the line segment to an AABB and test the resulting point against it.

Alternatively, get the length of the vector going from the ray origin to the resulting point and if it's longer, than the line segment, then it falls outside.

  • \$\begingroup\$ Great solution! The problem is solved. Initially I thought the ray is finite. \$\endgroup\$
    – mham
    Jul 4 '18 at 15:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.