I\'m trying to find the point of intersection between a sphere and a line but honestly, I don\'t have any idea of how to do so. Could anyone help me on this one ?
Express the line as an function of t
:
{ x(t) = x0*(1-t) + t*x1
{ y(t) = y0*(1-t) + t*y1
{ z(t) = z0*(1-t) + t*z1
When t = 0
, it will be at one end-point (x0,y0,z0)
. When t = 1
, it will be at the other end-point (x1,y1,z1)
.
Write a formula for the distance to the center of the sphere (squared) in t
(where (xc,yc,zc)
is the center of the sphere):
f(t) = (x(t) - xc)^2 + (y(t) - yc)^2 + (z(t) - zc)^2
Solve for t
when f(t)
equals R^2
(R
being the radius of the sphere):
(x(t) - xc)^2 + (y(t) - yc)^2 + (z(t) - zc)^2 = R^2
A = (x0-xc)^2 + (y0-yc)^2 + (z0-zc)^2 - R^2
B = (x1-xc)^2 + (y1-yc)^2 + (z1-zc)^2 - A - C - R^2
C = (x0-x1)^2 + (y0-y1)^2 + (z0-z1)^2
Solve A + B*t + C*t^2 = 0
for t
. This is a normal quadratic equation.
You can get up to two solutions. Any solution where t
lies between 0 and 1 are valid.
If you got a valid solution for t
, plug it in the first equations to get the point of intersection.
I assumed you meant a line segment (two end-points). If you instead want a full line (infinite length), then you could pick two points along the line (not too close), and use them. Also let t
be any real value, not just between 0 and 1.
Edit: I fixed the formula for B
. I was mixing up the signs. Thanks M Katz, for mentioning that it didn't work.