Game Development Reference
In-Depth Information
float b = 2.0F * Vector3.Dot(ray.Direction, vec);
float center = Vector3.Dot(vec, vec) - (entity.BoundingSphere.Radius *
float discriminant = (b * b) - (4.0F * center);
if (discriminant < 0.0F)
return false;
discriminant = (float)Math.Sqrt((double)discriminant);
float s0 = (-b + discriminant) / 2.0F;
float s1 = (-b - discriminant) / 2.0F;
if (s0 >= 0.0F || s1 >= 0.0F)
return true;
return false;
}
NOTE
The picking ray extends infinitely, so there is a possibility that multiple objects can be intersected.
The object closest to the camera is the one the user selected because it will always occlude the
other selected objects.
Improving Intersection Accuracy
Testing for object intersection with bounding sphere volumes works, and the tests
are straightforward and fast to compute. A disadvantage to using bounding sphere
volumes is a fair level of inaccuracy. Bounding sphere volumes are ideal for any
spherical object, although most of the time intersections are performed against an
arbitrary mesh, which means that selections can occur by clicking near the object.
A solution to this problem is to perform triangle intersections against all the poly-
gons within the arbitrary mesh. This process takes longer to compute, but the
results are much more accurate than bounding sphere volumes. For the purposes
of this example, we will use the built-in Mesh.Intersect() method of Managed
Direct3D to perform intersection at the polygon level. The picking ray is computed
in the same way as in the previous example, but the picking ray origin and direc-
tion are passed into the intersection method.