let:
- A(xA,yA,zA) and B(xB,yB,zB) be two different points on the line
- C(xC,yC,zC) be the center of the sphere
- r be the radius of the sphere
the cartesian equation of the sphere is:
- (x-xC)²+(y-yC)²+(z-zC)²=r²
let us write the parametric equation of the line (parameter d):
- x = xA + d*(xB-xA)
- y = yA + d*(yB-yA)
- z = zA + d*(zB-zA)
replacing in the sphere equation yields:
- (xA + d(xB-xA) - xC)²+(yA + d(yB-yA) - yC)²+(zA + d(zB-zA) - zC)²=r²
This is a quadratic equation in d, where the discrimant is:
with:
- a = (xB-xA)²+(yB-yA)²+(zB-zA)²
- b = 2*((xB-xA)(xA-xC)+(yB-yA)(yA-yC)+(zB-zA)(zA-zC))
- c = (xA-xC)²+(yA-yC)²+(zA-zC)²-r²
if Delta<0 then there is no intersection
if Delta==0 then there is a single intersection point (the line touches the sphere)
the unique solution is d=-b/2a (from there use the parametric equations to compute the coordinates of the intersection point)
if Delta>0 then there are a two intersection points
the solutions are d1=(-b-sqrt(Delta))/(2a) and d2=(-b+sqrt(Delta))/(2a) (from there use the parametric equations to compute the coordinates of the intersection points)
So what you have to do is:
- compute a, b, c, and then Delta using the formulas above
- depending on its value, compute d or (d1 and d2)
- compute the coordinates of the intersection points if there are any