Getting Started with XNA Game Studio 3.0 to develop video games

by Uditha Sampath Bandara



Part VIII.

 This month we`ll discuss about code and steps to use 3D coalition in a PC game.


 First you need to add 3d models and a 2d image to the content folder in a new XNA project.


Then you are able to write the code.

In the Game1.cs file initialize these variables.

Model model, colide_car, land;  // Initialize 3d model variables

Texture2D sunset;               // Initialize texture variable

KeyboardState lastKeyboardState;// Initialize keyboard

float distance= 0.0f;       // set distance to zero

float distance_left = 0.0f; // set distance_left  to zero

bool active = false;       // set active to false

float change_dir = 0.0f;   // set change_dir to zero;


Now in the LoadContent() method write code for loading the assest

      

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

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

land = Content.Load<Model>("floor");  //load the land model

sunset = Content.Load<Texture2D>("sunset");//load the 2d background


Then in the Update() method you can write this code segment.

 

lastKeyboardState = Keyboard.GetState();// get the user keyboard state

  

if (lastKeyboardState.IsKeyDown(Keys.Up)) //chack whether user press UP

{

 distance = distance + 2.8f;   // increase distance

}

   

 if (lastKeyboardState.IsKeyDown(Keys.Down))//chack whether user press DOWN

 {

 distance = distance - 2.8f;  //decrease distance

  }


if (lastKeyboardState.IsKeyDown(Keys.Left))//chack whether user press LEFT

 {             

distance_left = distance_left + 0.03f;  // increase distance_left

 }

          

if (lastKeyboardState.IsKeyDown(Keys.Right))//chack whether user press RIGHT

 {

 distance_left = distance_left - 0.03f;//decrease distance_left

}


In the Draw () method you can see the Changes by drawing the images and models.

 

GraphicsDevice device = graphics.GraphicsDevice; //set the device to the current graphic device

Viewport viewport = device.Viewport; // set the viewport to the current device viewport

spriteBatch.Begin();    //begin the spitebatch process

spriteBatch.Draw(sunset, new Vector2(0.0f, 0.0f), Color.White); //draw the image in 0,0 location

      

spriteBatch.End();      //end the spite batch process

   

float aspectRatio = (float)viewport.Width / (float)viewport.Height; //set the aspectRatio


//  Create camera matrices with substracting distance

          

Matrix world = Matrix.CreateRotationY(-20.42f) *

 

Matrix.CreateTranslation(2000.0f-distance, 0.0f, 0.0f)

                *Matrix.CreateRotationY(distance_left);

 

           

//  Create view

          

Matrix view = Matrix.CreateLookAt(new Vector3(3750,800, 60),

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

          

 //  Create projection


Matrix projection = Matrix.CreatePerspectiveFieldOfView(1, aspectRatio, 1, 100000);

     

 // create transform Matrix

         

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

        

 model.CopyAbsoluteBoneTransformsTo(transforms);

   

// Draw the main car.

         

  foreach (ModelMesh mesh in model.Meshes)

  {

  foreach (BasicEffect effect in mesh.Effects)

 

 {

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

 effect.View = view;

 effect.Projection = projection;

 effect.LightingEnabled = true;

 effect.DirectionalLight0.Enabled = true;

 effect.DirectionalLight0.Direction = Vector3.Left;  //set the directinal lighting

 effect.DirectionalLight0.DiffuseColor = Vector3.One;

GraphicsDevice.RenderState.DepthBufferEnable = true;  //set the grapics card rendering to depthbuffer enable

 GraphicsDevice.RenderState.AlphaBlendEnable = false;

GraphicsDevice.RenderState.AlphaTestEnable = false;

 }

 mesh.Draw(); // draw the player car

 

 }


 // For the AI car add the change_dir

          

Matrix world2 = Matrix.CreateRotationY(0.42f) *

Matrix.CreateTranslation(100.0f, 0.0f, 0.0f+change_dir);

Matrix[] transforms2 = new Matrix[colide_car.Bones.Count];

       

colide_car.CopyAbsoluteBoneTransformsTo(transforms2);

 

// Draw the AI car.

          

 foreach (ModelMesh mesh in colide_car.Meshes)

 {

foreach (BasicEffect effect in mesh.Effects)

   {

 effect.World = transforms2[mesh.ParentBone.Index] * world2;

 effect.View = view;

 effect.Projection = projection;

 effect.LightingEnabled = true;

 effect.DirectionalLight0.Enabled = true;

 effect.DirectionalLight0.Direction = Vector3.Left; //set the directinal lighting

 effect.DirectionalLight0.DiffuseColor = Vector3.One;

 GraphicsDevice.RenderState.DepthBufferEnable = true; //set the grapics card rendering to depthbuffer enable

 GraphicsDevice.RenderState.AlphaBlendEnable = false;

 GraphicsDevice.RenderState.AlphaTestEnable = false;

 }

   mesh.Draw(); //draw the AI car

  }

 

 #region chack coolition

 //collition detection


//Create a BoundingSphere for car1 with its center point and meshes BoundingSphere radies

BoundingSphere car1 = new BoundingSphere(new Vector3(2000.0f - distance, 0.0f, 0.0f), model.Meshes[0].BoundingSphere.Radius * 0.95f);


//Create a BoundingSphere for car2 with its center point and mesh BoundingSphere radies

 

BoundingSphere  car2 = new BoundingSphere(new Vector3(100.0f, 0.0f, 0.0f+change_dir),

colide_car.Meshes[0].BoundingSphere.Radius*0.95f);

 if (car2.Intersects(car1)) //chack whather car1 and AI car(car2) intersects

 {

  active = true;  //then set active true

   }

 

 if (active == false) //when active false

  {

  change_dir = 0.0f;  //set  change_dir to zero

 }

         

  else

 {

  change_dir = change_dir + 4.8f; // or increment the value

 }

#endregion


 #region draw land

 

 //set the  transforms Matrix

          

 Matrix[] transforms3 = new Matrix[land.Bones.Count];

 land.CopyAbsoluteBoneTransformsTo(transforms3);

 

 foreach (ModelMesh mesh in land.Meshes)

 {

 foreach (BasicEffect effect in mesh.Effects)

{

effect.World = transforms[mesh.ParentBone.Index] * Matrix.CreateRotationX(4.7f)                        *Matrix.CreateTranslation(400.0f,0.0f,0.0f);

 

 effect.View = view;

 effect.Projection = projection;    

                    graphics.GraphicsDevice.RenderState.DepthBufferEnable = true;

 

 //set the grapics card rendering to depthbuffer enable

 }


 mesh.Draw();  // Draw the land.

  }

 

  #endregion


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

 uditha.wordpress.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 ligting_car_xna_3._0

{

    /// <summary>

    /// This is the main type for your game

    /// </summary>

    public class Game1 : Microsoft.Xna.Framework.Game

    {

        GraphicsDeviceManager graphics;

        SpriteBatch spriteBatch;

 

        Model model, colide_car, land;  // Initialize 3d model variables

        Texture2D sunset;               // Initialize texture variable

        KeyboardState lastKeyboardState;// Initialize keyboard

         

        float distance= 0.0f;   // set distance to zero

        float distance_left = 0.0f; // set distance_left  to zero

        bool active = false;       // set active to false

        float change_dir = 0.0f;   // set change_dir to zero;


    public Game1()


        {

 

            Content.RootDirectory = "Content";

            graphics = new GraphicsDeviceManager(this);

        }

 

        /// <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);


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

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

            land = Content.Load<Model>("floor");         //load the land model

            sunset = Content.Load<Texture2D>("sunset");  //load the 2d background

        }

        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();


           lastKeyboardState = Keyboard.GetState();  // get the user keyboard state

 

           if (lastKeyboardState.IsKeyDown(Keys.Up)) //chack whether user press UP

            {

                distance = distance + 2.8f;   // increase distance

      

            }

 

           if (lastKeyboardState.IsKeyDown(Keys.Down))//chack whether user press DOWN

            {

              

                distance = distance - 2.8f;  //decrease distance

            }

 

           if (lastKeyboardState.IsKeyDown(Keys.Left))//chack whether user press LEFT

            {

                distance_left = distance_left + 0.03f;  // increase distance_left

           

            }

 

           if (lastKeyboardState.IsKeyDown(Keys.Right))//chack whether user press RIGHT

            {

                distance_left = distance_left - 0.03f;//decrease distance_left

            }


            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); // clear the graphic device

 

            GraphicsDevice device = graphics.GraphicsDevice; //set the device to the current graphic device

            Viewport viewport = device.Viewport; // set the viewport to the current device viewport


            spriteBatch.Begin();    //begin the spitebatch process

            spriteBatch.Draw(sunset, new Vector2(0.0f, 0.0f), Color.White); //draw the image in 0,0 location

            spriteBatch.End();      //end the spite batch process


            float aspectRatio = (float)viewport.Width / (float)viewport.Height; //set the aspectRatio


            //  Create camera matrices with substracting distance

            Matrix world = Matrix.CreateRotationY(-20.42f) * Matrix.CreateTranslation(2000.0f-distance, 0.0f, 0.0f)

                *Matrix.CreateRotationY(distance_left);

 

            //  Create view

            Matrix view = Matrix.CreateLookAt(new Vector3(3750,800, 60),

                                              new Vector3(0, 300, 0),

                                              Vector3.Up);

            //  Create projection

            Matrix projection = Matrix.CreatePerspectiveFieldOfView(1, aspectRatio,

                                                                    1, 100000);

 

            // create transform Matrix

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

 

            model.CopyAbsoluteBoneTransformsTo(transforms);

          

            // Draw the main car.

            foreach (ModelMesh mesh in model.Meshes)

            {

                foreach (BasicEffect effect in mesh.Effects)

                {

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

                    effect.View = view;

                    effect.Projection = projection;

                    effect.LightingEnabled = true;

                    effect.DirectionalLight0.Enabled = true;

                    effect.DirectionalLight0.Direction = Vector3.Left;  //set the directinal lighting

                    effect.DirectionalLight0.DiffuseColor = Vector3.One;

 

 

                    GraphicsDevice.RenderState.DepthBufferEnable = true;  //set the grapics card rendering to depthbuffer enable

                    GraphicsDevice.RenderState.AlphaBlendEnable = false;

                    GraphicsDevice.RenderState.AlphaTestEnable = false;

                }

 

               mesh.Draw(); // draw the player car

            }


            // For the AI car add the change_dir

            Matrix world2 = Matrix.CreateRotationY(0.42f) * Matrix.CreateTranslation(100.0f, 0.0f, 0.0f+change_dir);


            Matrix[] transforms2 = new Matrix[colide_car.Bones.Count];

            colide_car.CopyAbsoluteBoneTransformsTo(transforms2);

 

            // Draw the AI car.

            foreach (ModelMesh mesh in colide_car.Meshes)

            {

                foreach (BasicEffect effect in mesh.Effects)

                {

                    effect.World = transforms2[mesh.ParentBone.Index] * world2;

                    effect.View = view;

                    effect.Projection = projection;

 

                    effect.LightingEnabled = true;

                    effect.DirectionalLight0.Enabled = true;

                    effect.DirectionalLight0.Direction = Vector3.Left; //set the directinal lighting

                    effect.DirectionalLight0.DiffuseColor = Vector3.One;

 

                    GraphicsDevice.RenderState.DepthBufferEnable = true; //set the grapics card rendering to depthbuffer enable

                    GraphicsDevice.RenderState.AlphaBlendEnable = false;

                    GraphicsDevice.RenderState.AlphaTestEnable = false;


                }

 

               mesh.Draw(); //draw the AI car

            }

            #region chack coolition

               

            //collition detection


            //Create a BoundingSphere for car1 with its center point and meshes BoundingSphere radies

            BoundingSphere car1 = new BoundingSphere(new Vector3(2000.0f - distance, 0.0f, 0.0f), model.Meshes[0].BoundingSphere.Radius * 0.95f);

 

 

            //Create a BoundingSphere for car2 with its center point and mesh BoundingSphere radies

            BoundingSphere  car2 = new BoundingSphere(new Vector3(100.0f, 0.0f, 0.0f+change_dir), colide_car.Meshes[0].BoundingSphere.Radius*0.95f);

           

            if (car2.Intersects(car1)) //chack whather car1 and AI car(car2) intersects

            {

                active = true;  //then set active true

            }

 

            if (active == false) //when active false

            {

                change_dir = 0.0f;  //set  change_dir to zero

             }

            else

            {

                change_dir = change_dir + 4.8f; // or increment the value

             }

#endregion


            #region draw land

 

            //set the  transforms Matrix

            Matrix[] transforms3 = new Matrix[land.Bones.Count];

            land.CopyAbsoluteBoneTransformsTo(transforms3);


            foreach (ModelMesh mesh in land.Meshes)

            {

                foreach (BasicEffect effect in mesh.Effects)

                {

                    effect.World = transforms[mesh.ParentBone.Index] * Matrix.CreateRotationX(4.7f)

                        *Matrix.CreateTranslation(400.0f,0.0f,0.0f);

                    effect.View = view;

                    effect.Projection = projection;    

                    graphics.GraphicsDevice.RenderState.DepthBufferEnable = true;

                    //set the grapics card rendering to depthbuffer enable

                }

                 mesh.Draw();  // Draw the land.

            }

            #endregion

 

            base.Draw(gameTime);

        }

    }

}


This is the end of the using 3d coalition in a PC game tutorial.

Also source project is attached with this article.(http://digit.lk/downloads/Nov09/ligtingcarxna.rar)

Form the next tutorial you`ll learn about using VB.NET as the programming language in a XNA game.



Your rating: None Average: 4.8 (8 votes)

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.