Posts Tagged ‘math’

Ray-Sphere Intersection

August 6th, 2009 shyam No comments

A ray, \mathbf{r}(t), where \mathbf{o} is the origin of the ray, \mathbf{d} is the direction of the ray, and t is the distance along the ray:

\mathbf{r}(t) = \mathbf{o} + \mathbf{d} t

Equation of a sphere:

x^2 + y^2 + z^2 = \mathbf{p} \cdot \mathbf{p} = r^2

A point on the surface of the sphere, \mathbf{p}, and the center of the sphere, \mathbf{p_c}:

(\mathbf{p - p_c}) \cdot (\mathbf{p - p_c}) - r^2 = 0

Plug in the ray and solve for t:

(\mathbf{r}(t) - \mathbf{p_c}) \cdot (\mathbf{r}(t) - \mathbf{p_c}) - r^2 = 0

(t \mathbf{d} + \mathbf{o - p_c}) \cdot (t \mathbf{d} + \mathbf{o - p_c}) - r^2 = 0 \mathbf{d} \cdot \mathbf{d} t^2 + \mathbf{d} \cdot (\mathbf{o - p_c})t + \mathbf{d} \cdot (\mathbf{o - p_c})t + (\mathbf{o - p_c}) \cdot (\mathbf{o - p_c}) - r^2 = 0 \mathbf{d} \cdot \mathbf{d} t^2 + 2\mathbf{d} \cdot (\mathbf{o - p_c})t + (\mathbf{o - p_c}) \cdot (\mathbf{o - p_c}) - r^2 = 0

We now have a quadratic equation of the form At^2 + Bt + C = 0, where:

A = \mathbf{d \cdot d}

B = 2\mathbf{d \cdot (o - p_c)}

C = \mathbf{(o - p_c) \cdot (o - p_c)} - r^2

This can be plugged into the quadratic formula:

\frac{{ - B \pm \sqrt {B^2  - 4AC} }} {{2A}}

  • If the determinant, B^2 - 4AC, is negative, there exist no real roots and therefore there is no intersection.
  • If the determinant is 0, there is exactly one intersection; the ray is tangent to the sphere at this single point.
  • If the determinant is positive, there are two intersections. The ray penetrates the sphere: one point in, one point out.
  • If t < 0, the intersection is 'behind' the ray starting point.
Categories: General Tags: ,