1. Mathematics
We want to find the intersections of
-
A ray starting at point \(O\) and having direction \(\vec\Delta\).
-
A sphere with radius \(R\) centered at \(C\).
A sphere is defined as the set of all points \(P\) that are at a distance \(R\) from a center \(C\). Put into formula, each \(P\) must satisfy the following equation:
Making use of the dot product, the distance \(\mathrm{dist}(P, C)\) can be written as \(\sqrt{(P-C)\cdot(P-C)}\). The square root being rather bothersome, we square it away:
We know that \(P\) must reside on the ray, i.e. \(P\) must also satisfy
for some \(t\). Combining these two equations we get
Expanding and rearranging terms gives
We simplify the equation replacing the larger subexpressions by letters:
Thus giving as new equation
This quadratic equation can be solved using standard techniques.
-
Compute the discriminant:
\[D = b^2 - 4 \cdot a \cdot c\] -
If \(D < 0\), there are no solutions. This means the ray does not intersect the sphere.
-
If \(D \geq 0\), there are two solutions.
\[t_1 = \frac{-b-\sqrt{D}}{2 \cdot a} \qquad t_2 = \frac{-b+\sqrt{D}}{2 \cdot a}\]
Both \(t\) values indicate where on the ray the intersections lie. If \(t > 0\), the intersection lies in front of the beginning of the ray, i.e. these are generally the intersections that matter to us.
The actual intersection positions can be found using
2. Summary
Given
-
A ray starting at point \(O\) and having direction \(\vec\Delta\).
-
A sphere with radius \(R\) centered at \(C\).
The intersections can be found using the following steps:
-
Compute \(a = \vec\Delta \cdot \vec\Delta\).
-
Compute \(b = (O - C) \cdot \vec\Delta\).
-
Compute \(c = (O - C) \cdot (O - C) - R^2\).
-
Compute \(D = b^2 - 4 \cdot a \cdot c\).
-
If \(D < 0\), there are no intersections.
-
If \(D \geq 0\), there are two intersections:
\[t_1 = \frac{-b-\sqrt{D}}{2 \cdot a} \qquad t_2 = \frac{-b+\sqrt{D}}{2 \cdot a}\] -
The hit positions can be found using
\[P_1 = O + \vec\Delta \cdot t_1 \qquad P_2 = O + \vec\Delta \cdot t_2\] -
The normals are
\[\vec{N}_1 = \frac{P_1 - C}{R} \qquad \vec{N}_2 = \frac{P_2 - C}{R}\]