3D Collision Detection and Bounding Spheres

In the 2D section of this book, we covered a bounding-box algorithm for collision detection. Essentially, the algorithm uses an invisible box that surrounds an object and is used to determine if another object's box intersects with it. The bounding-box algorithm is one of the fastest collision-detection algorithms.

A similar approach is to use spheres surrounding the objects, rather than boxes. The same concept applies—you check an object's sphere to determine if it has collided with another object's sphere.

When you use models in XNA, bounding spheres are generated for you as part of the model. Each model contains one or more ModelMesh objects, and each ModelMesh has a property called BoundingSphere that defines a sphere surrounding that part of the model.

The tricky part of this is that when you apply a translation or scale to the model, the BoundingSphere of the model is not affected. So, to use the BoundingSphere specified in the model, you have to apply the same translations and scales to it that you apply to your model.

To do this, you'll be adding a collision-detection method inside the BasicModel class, to which you'll pass another BasicModel's model and world to check for collisions against all of its ModelMesh's BoundingSpheres.

This collision-detection method will receive a different model and world matrix in its parameter list. The method will loop through all of its own ModelMeshes and then loop through the other Model's ModelMesh ...

Get Learning XNA 3.0 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.