# Is this the correct way to detect ray-sphere intersection?

I have this java function that should return a true or false for any sphere passed to it if they intersect. However it seems to end being true a lot of the time when it shouldn't and false sometimes when it should be true.

It is possible however that i am passing incorrect data to the function. This was done with jPCT so the object SimpleVector is a vector with 3 variables.

public Boolean sphereIntersect(SimpleVector rayOrigin,SimpleVector rayDirection, SimpleVector sphereOrigin, float sphereRadius )
{
SimpleVector Q = new SimpleVector(sphereOrigin);
Q.sub(rayOrigin);

float c = sphereOrigin.length();
float v = Q.calcDot(rayDirection);

if (d < 0.0){
System.out.println("False");
return false;
}
System.out.println("True");
return true;

}


Replace

float c = sphereOrigin.length();


with

float c = Q.length();

• Yup, that was it, I made a change and forgot it required subsequent changes. Mar 10 '14 at 19:01
• Hey, I found this question very useful but I cannot seem to be able to properly use OP's function: "sphereIntersect(a, b.calcSub(a); new SimpleVector(0, 0, 0), MY_RADIUS);" Any pointers?
– N3sh
May 10 '16 at 20:16
• I don't understand. Do you have a problem with OPs code or with my fix? May 12 '16 at 15:38