Getting Started with XBOX 360 game development using Microsoft XNA.

Part IV


by Uditha Bandara


 

This month we`ll discuss about the code and steps to draw a 3d model in a XBOX360 game.

 

This will be the first step to develop games like Halo3 or GTAIV for the XBOX360 console.

First you need to use 3d modeling software like 3ds max of Maya to create 3d models.

Then you can export those models to the .x or .fbx format.

Steps to convert 3d model in to binary file was explained in my previous article.

http://digit.lk/09_may_xna

After you convert the model you can load that file to the content folder.

Right click on the content folder and Add->existing items


 

 

And select that file form the hard drive.

It could be .x and .fbx.

Now in the Game 1.cs you need to write code to draw 3D model in the screen.

First create a object form Model class to handle the model.

 

Model mymodel;

Then in the LoadContent() method you can load the image.

mymodel = Content.Load<Model>("car");

 

then in the Draw() method you can draw the model in the screen.

 

//create a new matrix and copy that tranfomation to 3d model

Matrix[] transforms = new Matrix[mymodel.Bones.Count];

 

//copy the absolute transforms to the car model.

mymodel.CopyAbsoluteBoneTransformsTo(transforms);

           

//use two foreach loops to loop through the mesh and mesh effect

foreach (ModelMesh mesh in mymodel.Meshes)

            {

 

     foreach (BasicEffect effect in mesh.Effects)

               {

  

//enable default lighting provides by XNA.

 effect.EnableDefaultLighting();

 

 //define the world matrix to locate the position

 effect.World = transforms[mesh.ParentBone.Index];

 

//define view matrix to set up the camara location

     effect.View = Matrix.CreateLookAt(new Vector3(550, 20

                               new Vector3(0, 300, 0), Vector3.Up);           

 

//define projection matrix to model projection ,aspect ratio,

and near and far plane distance.

  effect.Projection = Matrix.CreatePerspectiveFieldOfView(1,4.0f/3.0f,                                                           1, 10000); ;

                }

                mesh.Draw();

//draw the matrix

             }

 

now you can run the project by pressing F5 or by clicking the run button.

 

 


Final code of Game1.cs

/*

 content created by -uditha sampath bandara

 udithamail@yahoo.com

*/

 

using System;

using System.Collections.Generic;

using System.Linq;

using Microsoft.Xna.Framework;

using Microsoft.Xna.Framework.Audio;

using Microsoft.Xna.Framework.Content;

using Microsoft.Xna.Framework.GamerServices;

using Microsoft.Xna.Framework.Graphics;

using Microsoft.Xna.Framework.Input;

using Microsoft.Xna.Framework.Media;

using Microsoft.Xna.Framework.Net;

using Microsoft.Xna.Framework.Storage;

 

namespace _3d_in_XNA

{

    /// <summary>

    /// This is the main type for your game

    /// </summary>

    public class Game1 : Microsoft.Xna.Framework.Game

    {

        GraphicsDeviceManager graphics;

        SpriteBatch spriteBatch;

        Model mymodel;//create model object


        public Game1()

        {

            graphics = new GraphicsDeviceManager(this);

            Content.RootDirectory = "Content";

        }

 

        /// <summary>

        /// Allows the game to perform any initialization it needs to before starting to run.

        /// This is where it can query for any required services and load any non-graphic

        /// related content.  Calling base.Initialize will enumerate through any components

        /// and initialize them as well.

        /// </summary>

        protected override void Initialize()

        {

 

            base.Initialize();

        }

 

        /// <summary>

        /// LoadContent will be called once per game and is the place to load

        /// all of your content.

        /// </summary>

        protected override void LoadContent()

        {

            // Create a new SpriteBatch, which can be used to draw textures.

            spriteBatch = new SpriteBatch(GraphicsDevice);

 

            mymodel = Content.Load<Model>("car");// load the car model

            //set the scale as 15 in the model properties

        }

 

        /// <summary>

        /// UnloadContent will be called once per game and is the place to unload

        /// all content.

        /// </summary>

        protected override void UnloadContent()

        {

        

        }

        /// <summary>

        /// Allows the game to run logic such as updating the world,

        /// checking for collisions, gathering input, and playing audio.

        /// </summary>

        /// <param name="gameTime">Provides a snapshot of timing values.</param>

        protected override void Update(GameTime gameTime)

        {

            // Allows the game to exit

            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)

                this.Exit();


            base.Update(gameTime);

        }

        /// <summary>

        /// This is called when the game should draw itself.

        /// </summary>

        /// <param name="gameTime">Provides a snapshot of timing values.</param>

        protected override void Draw(GameTime gameTime)

        {

            GraphicsDevice.Clear(Color.Black);

 

            Matrix[] transforms = new Matrix[mymodel.Bones.Count];//create a new matrix and copy that tranfomation to 3d model

            mymodel.CopyAbsoluteBoneTransformsTo(transforms);


            //use two for each loop acess model mesh and its effects

            foreach (ModelMesh mesh in mymodel.Meshes)

            {

                 foreach (BasicEffect effect in mesh.Effects)

                {

                    effect.EnableDefaultLighting();

                    effect.World = transforms[mesh.ParentBone.Index];//add  varible to change the rotation of the model

                    // effect.World defines the world matrix

                   

effect.View = Matrix.CreateLookAt(new Vector3(550, 200, 600),  new Vector3(0, 300, 0),Vector3.Up);

//define view matrix to set up the camara location

 

  effect.Projection = Matrix.CreatePerspectiveFieldOfView(1,4.0f/3.0f,1, 10000);

//define projection matrix to crate distance to the model

  

 }

                mesh.Draw();//draw the matrix

             }

            base.Draw(gameTime);

        }

    }

}

 

Modify the code for 3d animation.

 

Also you can create a 3d animation to this example using these lines of codes.

First initilize a float variable to the animation.

 

float time;

then in Update() method get new values.


 time = (float)gameTime.TotalGameTime.TotalSeconds;

 

finally in the Draw()method add the time variable to change the rotation.

 

effect.World = transforms[mesh.ParentBone.Index] *Matrix.CreateRotationY(time * 0.42f);

 

then after you press F5 you are ready to play the animation.

Final code of Game1.cs with a 3d animation

 

/*

 content created by -uditha sampath bandara

 udithamail@yahoo.com

*/

 

using System;

using System.Collections.Generic;

using System.Linq;

using Microsoft.Xna.Framework;

using Microsoft.Xna.Framework.Audio;

using Microsoft.Xna.Framework.Content;

using Microsoft.Xna.Framework.GamerServices;

using Microsoft.Xna.Framework.Graphics;

using Microsoft.Xna.Framework.Input;

using Microsoft.Xna.Framework.Media;

using Microsoft.Xna.Framework.Net;

using Microsoft.Xna.Framework.Storage;

 

namespace _3d_in_XNA

{

    /// <summary>

    /// This is the main type for your game

    /// </summary>

    public class Game1 : Microsoft.Xna.Framework.Game

    {

        GraphicsDeviceManager graphics;

        SpriteBatch spriteBatch;

        Model mymodel;//create model object

 

        float time;  //use for 3d animation

        public Game1()

        {

            graphics = new GraphicsDeviceManager(this);

            Content.RootDirectory = "Content";

        }

        /// <summary>

        /// Allows the game to perform any initialization it needs to before starting to run.

        /// This is where it can query for any required services and load any non-graphic

        /// related content.  Calling base.Initialize will enumerate through any components

        /// and initialize them as well.

        /// </summary>

        protected override void Initialize()

        {

                        base.Initialize();

        }

 

        /// <summary>

        /// LoadContent will be called once per game and is the place to load

        /// all of your content.

        /// </summary>

        protected override void LoadContent()

        {

            // Create a new SpriteBatch, which can be used to draw textures.

            spriteBatch = new SpriteBatch(GraphicsDevice);

 

            mymodel = Content.Load<Model>("car");// load the car model

            //set the scale as 15 in the model properties

        }

 

        /// <summary>

        /// UnloadContent will be called once per game and is the place to unload

        /// all content.

        /// </summary>

        protected override void UnloadContent()

        {

                   }

 

        /// <summary>

        /// Allows the game to run logic such as updating the world,

        /// checking for collisions, gathering input, and playing audio.

        /// </summary>

        /// <param name="gameTime">Provides a snapshot of timing values.</param>

        protected override void Update(GameTime gameTime)

        {

            // Allows the game to exit

            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)

                this.Exit();

            time = (float)gameTime.TotalGameTime.TotalSeconds;//get time form the game time

             base.Update(gameTime);

        }

 

        /// <summary>

        /// This is called when the game should draw itself.

        /// </summary>

        /// <param name="gameTime">Provides a snapshot of timing values.</param>

        protected override void Draw(GameTime gameTime)

        {

            GraphicsDevice.Clear(Color.Black);

 

            Matrix[] transforms = new Matrix[mymodel.Bones.Count];//create a new matrix and copy that tranfomation to 3d model

            mymodel.CopyAbsoluteBoneTransformsTo(transforms);

                          //use two for each loop acess model mesh and its effects

            foreach (ModelMesh mesh in mymodel.Meshes)

            {

              foreach (BasicEffect effect in mesh.Effects)

                {

       effect.EnableDefaultLighting();      

       effect.World =transforms[mesh.ParentBone.Index] *Matrix.CreateRotationY(time * 0.42f);

 

//add  varible to change the rotation of the model


// effect.World defines the world matrix

      

 effect.View = Matrix.CreateLookAt(new Vector3(550, 200, 600),new Vector3(0, 300, 0),Vector3.Up);

//define view matrix to set up the camara location

        

effect.Projection = Matrix.CreatePerspectiveFieldOfView(1,4.0f/3.0f,1, 10000);

 //define projection matrix to crate distance to the model

                }

                mesh.Draw();//draw the matrix

            }

            base.Draw(gameTime);

        }

    }

}


This is the end of the draw 3d model and 3d animation tutorial.

Form next tutorial you learn about working with XBOX360 joystick using XNA.

Previous Article

 
Share/Save
No votes yet

Post new comment

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
Image CAPTCHA
Enter the characters shown in the image.