# Ray vs. sphere

A drawing of a ray intersecting a sphere in two dimensions.

In , a ray of origin and direction and an N-sphere of origin and radius intersect at given by:

where:

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).

## Surface normal

The surface normal at an intersection is given by:

## Normalized v

Notice that the expression for becomes appreciably simpler if :

## Derivation

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 .