Game Development Reference
In-Depth Information
We can square both sides of the equation to obtain the following equation.
This equation can then be written as a quadratic equation.
We can calculate the discriminant and use it to determine at first glance whether any
solutions exist. Ignoring t , we can calculate the discriminant with .
When the discriminant is less than zero, there are no solutions, so an intersection
did not occur.
When the discriminant is equal to zero, there is only one solution, which is gener-
ally a tangency. The solution for this case is given by the following equation:
When the discriminant is greater than zero, there are two solutions. Two solutions
for this case are given by the following equation:
Rays only extend in one direction (positive), so any solutions where t < 0 have to
be ignored. We just need to know if any solution was found, so we can skip the sec-
ond case altogether and jump right into the third case. If any solution is > 0, we
can safely say that an intersection was found.
The following code shows the intersection code for ray-sphere.
private bool IntersectRaySphere(Entity entity, int x, int y)
{
PickingRay ray = ComputePickingRay(entity, x, y);
Vector3 vec = ray.Origin - entity.BoundingSphere.Center;