O'Reilly logo

Learning XNA 4.0 by Aaron Reed

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 whether 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 whether 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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required