Line-Sphere Intersection

//p is a vector of some point on the line //l is a vector of the direction of the line //s is a vector of the center of the sphere //r is the radius of the sphere static boolean pos, neg; //Solutions public static boolean hits(double[] p, double[] l, double[] s, double r) { //Normalize l into a unit vector double norml = Math.sqrt(l[0]*l[0] + l[1]*l[1] + l[2]*l[2]); l[0] /= norml; l[1] /= norml; l[2] /= norml; //We're going to treat the line as though it went through (0, 0, 0) //So we modify the sphere center accordingly double[] c = new double[3]; c[0] = s[0] - p[0]; c[1] = s[1] - p[1]; c[2] = s[2] - p[1]; //The part under the radical double inside = dot(l, c)*dot(l, c) - dot(c, c) + r*r; //inside < 0 means no solution (no intersection) if(inside < 0) return false; //Get solutions //(p + pos*l) and (p + neg*l) are the two intersection points pos = dot(l, c) + Math.sqrt(inside); neg = dot(l, c) - Math.sqrt(inside); return true; } public static double dot(double[] a, double[] b) { return a[0]*b[0] + a[1]*b[1] + a[2]*b[2]; }