title: Ray-box Intersection Theory
body: <p>I wish to determine the intersection point between a ray and a box. The box is defined by its min 3D coordinate and max 3D coordinate and the ray is defined by its origin and the direction to which it points.</p>
  
  <p>Currently, I am forming a plane for each face of the box and I'm intersecting the ray with the plane. If the ray intersects the plane, then I check whether or not the intersection point is actually on the surface of the box. If so, I check whether it is the closest intersection for this ray and I return the closest intersection.</p>
  
  <p>The way I check whether the plane-intersection point is on the box surface itself is through a function </p>
  
  <pre><code>bool PointOnBoxFace(R3Point point, R3Point corner1, R3Point corner2)
  {
    double min_x = min(corner1.X(), corner2.X());
    double max_x = max(corner1.X(), corner2.X());
    double min_y = min(corner1.Y(), corner2.Y());
    double max_y = max(corner1.Y(), corner2.Y());
    double min_z = min(corner1.Z(), corner2.Z());
    double max_z = max(corner1.Z(), corner2.Z());
    if(point.X() &gt;= min_x &amp;&amp; point.X() &lt;= max_x &amp;&amp; 
       point.Y() &gt;= min_y &amp;&amp; point.Y() &lt;= max_y &amp;&amp;
       point.Z() &gt;= min_z &amp;&amp; point.Z() &lt;= max_z)
       return true;
  
    return false;
  }
  </code></pre>
  
  <p>where <code>corner1</code> is one corner of the rectangle for that box face and <code>corner2</code> is the opposite corner. My implementation works most of the time but sometimes it gives me the wrong intersection. Please see image:</p>
  
  <p><img src="https://imgur.com/vYKAi.jpg" alt="alt text"></p>
  
  <p>The image shows rays coming from the camera's eye and hitting the box surface. The other rays are the normals to the box surface. It can be seen that the one ray in particular (it's actually the normal that is seen) comes out from the "back" of the box, whereas the normal should be coming up from the top of the box. This seems to be strange since there are multiple other rays that hit the top of the box correctly.</p>
  
  <p>I was wondering if the way I'm checking whether the intersection point is on the box is correct or if I should use some other algorithm.</p>
  
  <p>Thanks.</p>