Showing posts with label XNA 3D GAME TUTORIAL. Show all posts
Showing posts with label XNA 3D GAME TUTORIAL. Show all posts

Saturday, July 6, 2013

XNA 3D Simple Collision Detection with BoundingSphere



First declare a Model for the 3ds max object you want to use..

Model 3dsMaxModel, 3dsMaxHouseModel;
Vector3 ModelPosition, housePosition;


In your load content..

//SET THE MODEL INTO THE VARIABLES
3dsMaxModel = Content.Load("ModelName");
3dsMaxHouseModel= Content.Load("ModelName");
//SET THE POSITION
ModelPosition = Vector3.Zero;
housePosition = new Vector3(10,1,10);


Create a new method for checking the collision
The method will use 4 variables, it is pretty much self explanatory.
public void CollisionTest(Model _model1, Model _model2, Vector3 _model1Position, Vector3 _model2Position){
//Create a new bounding sphere for the first model..

BoundingSphere obj = _model1.Meshes[0].BoundingSphere; // Get the bounding sphere for the mesh
obj.Center = _model1Position; //SETS the center of the bounding sphere

//For the second object..
BoundingSphere obj2 = _model2.Meshes[0].BoundingSphere;
obj2.Center = _model2Position;

if(obj.Intersects(obj2)){
//DO SOMETHING, This is where we are gonna code what happens to the model when it intersects with another model
}
}


And be sure to put use the CollisionTest in your update method..

CollisionTest(3dsMaxModel,3dsMaxHouseModel,ModelPosition,housePosition);

Saturday, June 29, 2013

II. The camera is your Eyesight 3D XNA



This is a continuation of the first topic.
At the first topic, we never used a camera.
We set the mesh view to default.
Let's create a camera that will be able to move freely in the 3D space..
Add the following lines to the top of your class.

 Matrix viewMatrix=Matrix.Identiy, rotationMatrix = Matrix.Identiy; // View matrix is your eyesight in the 3d space, rotation matrix is the rotation of the camera in the value of matrix
 Vector3 cameraPosition= Vector3.Zero; //Camera position set to 0
Vector3 cameraOffset = new Vector3(10, 0, -10); //Set up a vector3 that will be added to the cameraposition and serves as the camera target
Vector3 cameraRotation = Vector3.Zero; //camera rotation is the rotation of camera in Vector3, we'll update the value of this based on input
Vector3 cameraVelocity = Vector3.Zero; // The velocity of the camera
float movespeed = 5f; // Movespeed of camera

At your update ,set the value of  view matrix and a rotation matrix.


 cameraPosition = Vector3 .Transform (cameraPosition ,rotationMatrix );
Transform the cameraposition with the rotation of the camera
 viewMatrix = Matrix.CreateLookAt(cameraPosition, cameraPosition + cameraOffset, Vector3.Up);
//set the view matrix, to create a look at we need the camera position, the target, the direction of camera view


At your draw method, replace the

effect.View = Matrix.Identity 
to
 effect.View = viewMatrix;

With this, the value of house view will be equal to the viewMatrix..

Next, we need to update the camera..
On your update method, create a set of if statements..

[updating in progress]



I. Drawing 3D models - XNA

DRAWING 3D MODELS XNA TUTORIAL
"Welcome to the 3D world"

Before we start writing 3d methods, I'm going to explain some basic concepts in 3D space..
When we say 3D, we're talking about x,y,z. A model or game object will have 3d position and 3d rotation. Please see attached image.




Example, try looking in the image. Move your body to your right, left. Look up, down.  Move your head closer to the monitor, farther..
X = left/ right
Y = down/ up
Z = zoom/scale


Let's start making a game using 3 Dimensions.  Create a new project, call it myFirst3dGame
Step 1 : Download and importing the Content files.
house model

Step 2: Creating a class for your gameObject

On your solutionExplorer (View > Solution Explorer)
Right click Your myFirst3dGame project > Add > new class.. Name it gameObject

[The look of our solution so far]

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna .Framework .Graphics ;
namespace myFirst3dGame
{
    class gameObject
    {
        public Vector3 position = Vector3 .Zero ;
        public Vector3 rotation = Vector3.Zero;
        public Model model;
        public bool alive = true;
        public Vector3 velocity = Vector3.Zero;
    }
}

As you can see, instead of using vector2, we used vector3 for the position and even the rotation. We need to take the Z axis in our account. Model is the data type of 3D model.

Now go to your Game1.cs..
Step 3: Declaring your variables.
At the top of your class, declare:

gameObject house;
Matrix projectionMatrix; //projection matrix is usually used for camera. Matrix are used for viewing purposes.
Go to your loadcontent and set up the values of variables..

house = new gameObject();
house.alive =true;
house.model = Content.Load("house");
projectionMatrix = Matrix.CreatePerspectiveFieldOfView(MathHelper.ToRadians (45f), GraphicsDevice.Viewport.AspectRatio, 1, 700f); // Create a perspective field of view in Y position, set to 45f degrees and convert to radians.
//1 is the near sight position, and 700f farplane
house.position.Z = -30;



At your Draw method

  foreach (ModelMesh mesh in house.model.Meshes) //for each mesh in house meshes
            {
                foreach (BasicEffect effect in mesh.Effects) //for each basic effect in house meshes
                {

                    effect.View = Matrix.Identity ; //Set view to default
                    effect.World = Matrix.CreateTranslation(house.position) * Matrix.CreateRotationX(house.rotation.Y); //translate the object to the 3d space
                    effect.EnableDefaultLighting(); //enable default light sources
                    effect.Projection = projectionMatrix; //project the model according to the value of gameobject
                    
                    
                }
                mesh.Draw(); //draw the mesh
            }


RUN THE GAME!!

[Welcome to the 3D World]


SOURCE CODE

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;

namespace myFirst3dGame
{
    
    public class Game1 : Microsoft.Xna.Framework.Game
    {
        GraphicsDeviceManager graphics;
        SpriteBatch spriteBatch;
        gameObject house;
        Matrix viewMatrix, projectionMatrix;
        Vector3 cameraPosition;
        public Game1()
        {
            graphics = new GraphicsDeviceManager(this);
            Content.RootDirectory = "Content";
        }


        protected override void Initialize()
        {
            // TODO: Add your initialization logic here

            base.Initialize();
        }

  
        protected override void LoadContent()
        {
            
            spriteBatch = new SpriteBatch(GraphicsDevice);
            house = new gameObject();
            house.model = Content.Load("house");
            projectionMatrix = Matrix.CreatePerspectiveFieldOfView(MathHelper.ToRadians (45f), GraphicsDevice.Viewport.AspectRatio, 1, 700f);
            house.position.Z = -30;
        }

      
        protected override void UnloadContent()
        {
           
        }

    
        protected override void Update(GameTime gameTime)
        {
       

            base.Update(gameTime);
        }

  
        protected override void Draw(GameTime gameTime)
        {
            GraphicsDevice.Clear(Color.CornflowerBlue);

            foreach (ModelMesh mesh in house.model.Meshes)
            {
                foreach (BasicEffect effect in mesh.Effects)
                {

                    effect.View = Matrix.Identity ;
                    effect.World = Matrix.CreateTranslation(house.position) * Matrix.CreateRotationX(house.rotation.Y);
                    effect.EnableDefaultLighting();
                    effect.Projection = projectionMatrix;
                    
                    
                }
                mesh.Draw();
            }

            base.Draw(gameTime);
        }
    }
}


Download the source code here.