0
kicks
Getting started with XNA - Drawing a 3D Model
In the previous tutorials, we’ve learned how to draw primitives and 2D textures. It’s time we step up to drawing a 3D model. To start with this tutorial you’ll need the following source code. It’s just an empty project containing our heads up display. Our 3D model is also located in the content folder. When you click on the forklift.fbx file, notice that it uses the Autodesk FBX - XNA Framework importer and Model - XNA Framework processor.
Forklift.fbx is a 3d model which has been exported from 3D Studio Max. You can find screenshots of the model and the export below.
ForkliftForklift WireframeForkliftForklift WireframeForklift Export
So let’s get started! Add a class to your project and call it Forklift.cs. Then adjust the class so it inherits from DrawableGameComponent. This makes sure that our LoadGraphicsContent, Update and Draw method will be called automatically. When you’re writing a full game, you’ll probably write your own component based system, but for this tutorial, DrawableGameComponent will do just fine.
public class Forklift : DrawableGameComponent
Then we’ll add 3 variables to our class. The first containing the content manager, which will load our content. The second a variable which will contain our model, and last but not least, a variable which will contain the bone transforms of our model (the transform of each bone relative to the parent bone).
// A variable containing our content manager
private ContentManager _content;
// Our model
private Model _model;
// Array holding all the bone transform matrices for the entire model.
// We could just allocate this locally inside the Draw method, but it
// is more efficient to reuse a single array, as this avoids creating
// unnecessary garbage.
Matrix[] _boneTransforms;
Then add the following constructor, where we’ll pass the Game class to the base class and save a reference to our content manager:
public Forklift(Game game, ContentManager content)
: base(game)
{
_content = content;
}
Now there are 2 things we have to do left: load the model and draw it. We’ll load the model in the LoadGraphicsContent method.
protected override void LoadGraphicsContent(bool loadAllContent)
{
_model = _content.Load(”Content/forklift”);
// Allocate the transform matrix array.
_boneTransforms = new Matrix[_model.Bones.Count];
//rotate the model 90 degrees
_model.Root.Transform *= Matrix.CreateRotationY(MathHelper.ToRadians(90));
base.LoadGraphicsContent(loadAllContent);