Ray vs. sphere
In , a ray of origin and direction and an N-sphere of origin and radius intersect at given by:
If the expression under the square root is negative, there is no intersection. If it's zero, and there is only one intersection.
Notice that since is the distance to intersection, corresponds to the closer one and to the further. Depending on the application, you might want to discard negative 's (intersections “behind” the ray).
The surface normal at an intersection is given by:
Notice that the expression for becomes appreciably simpler if :
Notice that the point of intersection lies somewhere on the line defined by the ray:
for some real . It also lies somewhere on the sphere:
for some vector of length . Combining the two equations and solving for yields:
To simplify the algebra, substitute :
Since only the length of is known, the only thing that can be done at this point is equating the norms of both sides. Squared norms are more convenient in this particular case:
Solving the quadratic equation and simplifying:
As with any quadratic equation, there is no real solution if the expression under the square root is negative and if it's zero, the solutions coincide.
Notice that is perpendicular to the sphere at an intersection. Normalizing this vector yields the surface normal .