Page 1 of 3
This tutorial is a very brief introduction in collecting keyboard and mouse input in your XNA game. It is an extension of a tutorial from Microsoft, Tutorial 2: Making Your Model Move Using Input. In that tutorial, you collect input from a Xbox 360 controller.
First, we will modify our game code to collect keyboard input. We would like to control the rotation of our model if the user presses any of the arrow keys, and we also want to use the spacebar to control resetting the model location.
1. In Microsoft's tutorial, we used a variable called modelRotation. We are going to get rid of that variable and create 2 new ones in its place, modelRotationX and modelRotationY. We need these so we can manipulate rotation in more than one direction. The only change we are making to the previous Draw method is to apply an additional rotation on the Y axis. This takes place in our call to Matrix.CreateRotationY. Paste the following code just above and over the existing Draw method in your tutorial code.
//Position of the model in world space, and rotation
Vector3 modelPosition = Vector3.Zero;
float modelRotationX = 0.0f;
float modelRotationY = 0.0f;
//Position of the Camera in world space, for our view matrix
Vector3 cameraPosition = new Vector3(0.0f, 50.0f, 5000.0f);
//Aspect ratio to use for the projection matrix
float aspectRatio = 640.0f / 480.0f;
protected override void Draw(GameTime gameTime)
//Copy any parent transforms
Matrix transforms = new Matrix[myModel.Bones.Count];
//Draw the model, a model can have multiple meshes, so loop
foreach (ModelMesh mesh in myModel.Meshes)
//This is where the mesh orientation is set, as well as our camera and projection
foreach (BasicEffect effect in mesh.Effects)
effect.World = transforms[mesh.ParentBone.Index] * Matrix.CreateRotationX(modelRotationX)
effect.View = Matrix.CreateLookAt(cameraPosition, Vector3.Zero, Vector3.Up);
effect.Projection = Matrix.CreatePerspectiveFieldOfView(MathHelper.ToRadians(45.0f),
aspectRatio, 1.0f, 10000.0f);
//Draw the mesh, will use the effects set above.