## Bounding Shapes in 3D

In terms of bounding shapes we again have a ton of options. Figure 11-12 shows some of the more popular bounding shapes in 3D programming.

Triangle Mesh: This bounds the object as tightly as possible. However, colliding two objects based on their triangle meshes is computationally heave.

Axis Aligned Bounding Box: This bounds the object loosely. It is a lot less computationally intensive than a triangle mesh.

Bounding Sphere: This bounds the object even less well. It is the fastest way to check for collisions.

Another problem with triangle meshes and bounding boxes is that we have to reorient them whenever we rotate or scale the object, just as in 2D. Bounding spheres on the other hand don't need any modification if we rotate an object. If we scale an object, we just need to scale the radius of the sphere, which is a simple multiplication.

The mathematics of triangle mesh and bounding box collision detection can be pretty involved. For our next game, bounding spheres will do just fine. There's also a little trick we can apply which we already used in Super Jumper: to make the bounding sphere fit a little better we make it smaller than the graphical representation. Figure 11-13 shows you how that could look in case of the space ship.

Figure 11-13. Making the bounding sphere smaller to better fit an object

That's of course a very cheap trick, but it turns out that in many situations it is more than sufficient to keep up the illusion of mostly correct collision detection.

So how do we collide two spheres with each other? Or rather, how do we test for overlap? It works exactly the same as in the case of circles! All we need to do is measure the distance from the center of one sphere to the center of the other sphere. If that distance is smaller than the two radii of the spheres added together, then we have a collision. Let's create a simple Sphere class. Listing 11-13 shows you the code.

## Post a comment