## Ray-Sphere Intersection

10.01.2018 19:02 by chris

When developing atmospheric scattering shaders, we will need to calculate intersection points between rays and spheres. So here is how we can do that.

**Defining a ray**

To define a ray, we specify two vectors: One point o, which goes from zero to a point on the ray and another one d, which goes along the ray and defines therefore the ray’s direction. The direction vector is multiplied by an argument t. When varying t, we can reach any point on the ray. *Now you might say, that we did not define a ray, but a line. The only difference between rays and lines is, that t has a minimum value for rays. A line goes from -infinity to infinity, while a ray has a starting point and goes to infinity from there. In our use case, that’s not that important tough.*

**Defining a sphere**

To define a sphere, we need to specify a center point c and a radius r. All points on a sphere are points, which have a distance to the center point equally to the sphere’s radius. So a sphere’s definition can be: If we can assume, that the center of the sphere is at the origin of our coordinate system, the equation simplifys to , so “all vectors with a certain length r”.

**Intersecting both**

In our use case, we will have the spheres always centered, so we can use the easier version of the sphere definition. Inserting the ray definition into the sphere definition yields:

I replaced t with because now it is not a varying parameter anymore. Instead it is a symbol for all values which fulfill this equation (a ray can hit a sphere zero, one or two times).

Image a vector , then there is:

From the definition of the dot product and

So there is

To apply this to the intersection, we need to square it first:

To make the calculation easier we assume, that is normalized: So the denominators above are one and are left out.

Now we use the reduced quadratic formula to solve the equation for :

The discriminant is

So the cheapest way to calculate the intersection point is:

with

Keep in mind, that has to be normalized!