Drawing an XNA Model bounding box

If you’re making a level editor, or perhaps a model viewer, it can sometimes be useful to see a visualisation of the 3D space a model sits within. It might also be handy if you use bounding boxes for physics, and you want to check that the bounding box is really where you think it is.

Creating the bounding box

First (and hopefully not surprisingly), you’ll need the bounding box itself. XNA has a nice structure for this, helpfully named BoundingBox. If you already have access to one of these for your model, then you can skip to the next section. If you only have a Model object, and want to creating a bounding box, then you can use this code. Note that the ModelMesh class has a BoundingSphere property. XNA allows us to create a BoundingBox from a BoundingSphere, but that wouldn’t be a tight fit - it would be larger than necessary. So I prefer to go back to the original vertices and use them to create the bounding box. Step 1, then, is to extract the vertex positions from the Model:

In XBuilder, I actually create a bounding box for each ModelMesh, but the general principle is the same.

We now have a BoundingBox for our Model, so we can get ready to draw it.

Preparing to draw the bounding box

You could draw an actual box, with solid lines. I prefer the approach taken by most 3D modelling packages of just drawing the corners. This is a bit more involved, and sorry for the long code snippet. If anybody knows a cleverer way of doing this, please let me know! First we need a class to hold the vertex and index buffers we’re going to create: