# Ray-box intersection problem

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

• The ray is infinite, the start and end point are only there to define it Jul 4 '18 at 10:08
• @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. :) Jul 4 '18 at 11:42