• Advertisement
Sign in to follow this  

ray to box collision detection problems

This topic is 2564 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts


I am attempting to use a ray to box intersection within my program. It initially seems fine and seems to work ok for the object I am moving around my scene. It can calculate how far away from the object I am etc. I am also attempting to use it within a camera. The idea being to be able to fire a ray in the direction the camera is facing. If this hits the box return true else return false.

I am assuming it is something I am doing with the camera that is causing me errors?

Maybe to do with the way I am looking down the axis? I seem to either be able to get false positive most of the time or no positive.

The code for my ray to box intersection is

bool Collision::rayToBoxCollision(float boxX1,float boxX2, float boxY1, float boxY2, float boxZ1, float boxZ2, float rayStartX, float rayStartY, float rayStartZ,float rayDirectionX,float rayDirectionY, float rayDirectionZ, float angleOfRotation)

float tNear = -500;
float tFar = 500;
float T1Final;
float T2Final;
float T1;
float T2;
j = 0; // keep track of box edges

float boundingBox[] = {boxX1, boxX2,boxY1,boxY2,boxZ1,boxZ2}; // set up bounding box points
float raystartPoint[] = {rayStartX,rayStartY,rayStartZ}; // ray starting vector
float rayDirectionVector[] = {rayDirectionX,rayDirectionY,rayDirectionZ}; // ray direction vector
bool collision[] = {0,0,0};

for(int i = 0; i<3; i++) // loop around all arrays
tNear = -500;
tFar = 500;

if(raystartPoint == 0) // if ray is parrallel to box
if(raystartPoint < boundingBox[j] || raystartPoint > boundingBox[j+1]) // if its not within the box boundry
collision = false;
collision = true;

if(rayDirectionVector == 0)
rayDirectionVector += 1;

T1 = boundingBox[j] - raystartPoint;
T1Final = T1/rayDirectionVector; // calculate intersection Distance between bottom

T2 = boundingBox[j+1] - raystartPoint;
T2Final = T2/rayDirectionVector; //calculate intersection distance top

if(T1Final>T2Final) // if top and bottom are the wrong way round swap
float temp = T2Final;
T2Final = T1Final;
T1Final = temp;

if(T1Final>tNear) //clamp near collision to t1
tNear = T1Final;

if(T2Final < tFar) // clamp far collision to t2
tFar = T2Final;

rayTfar = tFar;
rayTNear = tNear;

rayArray = tNear;
rayArray[i+1] = tFar;

j += 2;

if(tNear > tFar)
collision = false;
else if(tFar<0)
collision = false;
collision = true;

if(collision[0] == true && collision[1] == true && collision[2] == true) // check x,y and z axis are all true
return true;
return false;


Is there something wrong here that I have missed? or is it the way I am shooting the ray from the camera?

Any help greatly appreciated

Share this post

Link to post
Share on other sites
Sign in to follow this  

  • Advertisement