Showing posts with label XNA. Show all posts
Showing posts with label XNA. Show all posts

Thursday, February 20, 2014

Game development with C# and XNA FRAMEWORK

Flappy birds Ripoff

[Screenshot]

[Video]
[Source code of unfinished game activity @ Game development with c# and XNA framework..]

Requirements:
XNA Game studio FRAMEWORK
Visual Studio
Download XNA FRAMEWORK REDIST [To run exe file]

Download Executable game here (requires XNA FRAMEWORK REFRESH REDIST)
Download Source code here


[ Download Instructions]
Press File > Download or Ctrl+s to save file
[Error ? opening the solution Click HERE]






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

Monday, July 1, 2013

VII. Improve our tank game - Additional Updates XNA

Let's add additional updates in this project.
Open your project and locate the AI.(gameTime);
We don't want the AI to move when we're already dead , or the AI is dead. So, set a condition before updating the AI

//UPDATE METHOD
if (enemy.alive && player.alive)
{
      AI(gameTime);
}

Next, add a bool to your project called hasstart.
   bool hasstart = false;

Next go to your Game ()method, make the screen larger for more gameplay space.
 public Game1()
        {
            graphics = new GraphicsDeviceManager(this);
            Content.RootDirectory = "Content";
            graphics.PreferredBackBufferHeight = 768;
            graphics.PreferredBackBufferWidth = 1024;
            graphics.ApplyChanges();
        }

//UPDATE METHOD
   if (hasstart) //IF THE GAME HAS STARTED, UPDATE THE GAME OBJECTS, METHODS AND THE GAME
            {
                updateTank();
                if (enemy.alive && player .alive )
                {
                    AI(gameTime);
                }
                if (player.alive)
                {
                    tempposition = player.position;
                    if (currentKeyboardState.IsKeyDown(Keys.Right) && oldKeyboardState.IsKeyDown(Keys.Right))
                    {
                        player.rotation += 0.1f;
                    }
                    if (currentKeyboardState.IsKeyDown(Keys.Left) && oldKeyboardState.IsKeyDown(Keys.Left))
                    {
                        player.rotation -= 0.1f;
                    }
                    if (currentKeyboardState.IsKeyDown(Keys.Up) && oldKeyboardState.IsKeyDown(Keys.Up))
                    {
                        player.position += player.velocity * moveSpeed;
                        player.position.X = MathHelper.Clamp(player.position.X, player.texture.Width / 4, GraphicsDevice.Viewport.Width - player.texture.Width / 4);
                        player.position.Y = MathHelper.Clamp(player.position.Y, player.texture.Height / 4, GraphicsDevice.Viewport.Height - player.texture.Height / 4);
                        soundManager.soundBank.PlayCue("move");
                    }
                    if (currentKeyboardState.IsKeyDown(Keys.Down) && oldKeyboardState.IsKeyDown(Keys.Down))
                    {

                        player.position -= player.velocity * moveSpeed;
                        player.position.X = MathHelper.Clamp(player.position.X, player.texture.Width / 4, GraphicsDevice.Viewport.Width - player.texture.Width / 4);
                        player.position.Y = MathHelper.Clamp(player.position.Y, player.texture.Height / 4, GraphicsDevice.Viewport.Height - player.texture.Height / 4);

                    }
                    if (currentKeyboardState.IsKeyDown(Keys.Space) && oldKeyboardState.IsKeyUp(Keys.Space))
                    {
                        fireBullets();
                    }

                }

                if (enemy.life <= 0)
                {
                    enemy.alive = false;
                }
                if (player.life <= 0)
                {
                    player.alive = false;
                }
                detectCollisionsAgainstObject(player, enemy);
            }
            if (currentKeyboardState.IsKeyDown(Keys.Enter) && oldKeyboardState.IsKeyUp(Keys.Enter) && hasstart == false)
            {
                //IF THE PLAYER PRESSED ENTER KEY AND THE GAME HASNT STARTED , SET THE GAME TO START
                hasstart = true;
            }


NEXT, INFORM THE USER HOW TO START THE GAME
//DRAW METHOD, EDIT YOUR DRAW METHOD

 protected override void Draw(GameTime gameTime)
        {
            GraphicsDevice.Clear(Color.CornflowerBlue);
          
            spriteBatch.Begin();
            spriteBatch.Draw(background , Vector2 .Zero ,
               null, Color.White, 0f,
              Vector2 .Zero ,
               2f, SpriteEffects.None, 0);
            if (enemy.alive)
            {
                spriteBatch.Draw(enemy.texture, enemy.position,
                   null, Color.White, enemy.rotation,
                   new Vector2(enemy.texture.Width / 2, enemy.texture.Height / 2),
                   0.5f, SpriteEffects.None, 0);
            }
            else
            {
                spriteBatch.DrawString(Content.Load("font"), "YOU WIN!: ", new Vector2(GraphicsDevice.Viewport.Width / 2-14, GraphicsDevice.Viewport.Height / 2), Color.Red);
hasstart= false;
            }
            SpriteFont font = Content.Load("font");
            if(!hasstart )
                spriteBatch.DrawString(font, "PRESS ENTER TO START GAME", new Vector2(GraphicsDevice.Viewport.Width / 2 - font.MeasureString("PRESS ENTER TO START GAME").X / 2, GraphicsDevice.Viewport.Height / 2), Color.White);
         
            if (player.alive)
            {
                spriteBatch.Draw(player.texture, player.position,
                null, Color.White, player.rotation,
                new Vector2(player.texture.Width / 2, player.texture.Height / 2), 0.5f, SpriteEffects.None, 0);
            }
            else
            {
                spriteBatch.DrawString(Content.Load("font"), "GAME OVER!: ", new Vector2 (GraphicsDevice .Viewport .Width /2 -14, GraphicsDevice .Viewport .Height /2),Color.Red);
hasstart = false;
           
            }
            updateBullets();
            spriteBatch.DrawString(Content.Load("font"), "BULLETS: " + player.numberOfBullets.ToString() + " " + player .rotation .ToString (), Vector2.Zero, Color.White);
            spriteBatch.DrawString(Content.Load("font"), "ENEMY LIFE: " + enemy.life.ToString(),
             new Vector2(GraphicsDevice .Viewport .Width - 200 ,0), Color.White);
           
            spriteBatch.End();
            foreach (gameObject explode in Explosion)
            {
                drawExplosion(explode);
            }
            base.Draw(gameTime);
        }
         

NOW CREATE A RECTANGLE METHOD THAT WILL DRAW THE LIFE OF THE PLAYER

    public Rectangle life(Vector2 position, int hp, int border )
         {
             
             int w = 1;
             int h = 10;
             return new Rectangle((int)position.X - border , (int)position.Y - border , w * hp +border *2 ,h + border*2 );
         }
         public void drawRectangle(bool alive)
         {
             Color hpColor;
             if (alive)
             {
                 if (player.life < 30)
                 {
                     hpColor = Color.Red;
                 }
                 else
                 {
                     hpColor = Color.ForestGreen;
                 }
                 Texture2D bounds = new Texture2D(GraphicsDevice, 1, 2);
                 Color[] color = new Color[1 * 2];
                 for (int i = 0; i < color.Length; i++)
                     color[i] = Color.Black * 0.5f;
                 bounds.SetData(color);
                 spriteBatch.Draw(bounds, life(new Vector2(player.position.X - player.texture.Width / 4, player.position.Y - player.texture.Height / 3), 100, 2), Color.White);
                 bounds = new Texture2D(GraphicsDevice, 1, 1);
                 bounds.SetData(new Color[] { hpColor });
                 spriteBatch.Draw(bounds, life(new Vector2(player.position.X - player.texture.Width / 4, player.position.Y - player.texture.Height / 3), player.life, 0), Color.White);
             }

         }

THEN ADD IT TO YOUR DRAW METHOD

 drawRectangle(player .alive ); //PLACE IT BEFORE THE SPRITEBATCH.END



RUN THE GAME!!


[AI WONT UPDATE : PLAYER IS DEAD]

[WAIT FOR INPUT DEPENDING ON HAS START BOOL]

[HP BAR USING RECTANGLE METHOD]





VII. Improve our tank game - Adding Sound Files

[This topic is the continuation of the my previous 2D tutorial, Click Here to go to the main post.]
[How to create and use XACT audio File - To upload soon]
We're going to add a new class called soundManager, in your solution explorer. Add a new class name it soundManager.

Paste the following Codes inside the class, make sure the namespace is same with your Game1.cs namespace.

To use this class, we need the ff packages
using System;
using System.Collections.Generic;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Input;

namespace tankGame
{
    class soundManager
    {
        //Creates soundManager class methods, variables
        public AudioEngine audioEngine; //The engine that plays the sound.
        public WaveBank waveBank; //A collection of waves
        public Cue engineSound = null;
        public SoundBank soundBank; //A collection of Sounds
        public soundManager()
        {

        }
        public void loadcontent(ContentManager content)
        {
            audioEngine = new AudioEngine("Content/Audio/sound.xgs"); //Set's the location of the compiled XACT(xgs extension)
            waveBank = new WaveBank(audioEngine, "Content/Audio/Wave Bank.xwb"); //Compiled waveback (xwb extension)
            soundBank = new SoundBank(audioEngine, "Content/Audio/Sound Bank.xsb");//Compiled SoundBound(xsb)
        }
        public void Update(GameTime gameTime)
        {
            audioEngine.Update(); //UPDATES THE SOUND ENGINE
        }  
    }
}
To use this class, you must have a XACT FILE, a wavebank and soundbank which are within the xact file.
We successfully created a class that will play different sounds depending on input, what we need to do is to download and import the sound file(XACT) on our game content. To do this..

Download and unzip this on your game content..
Next go to your game content, to know your game content: View the attached image.

[Copy and paste the rar file> Extract Here]


[Add a folder called Audio Then import the sound files]

[Import it to the game. Add > existing item> browse to your game Content]


[After importing, On your properties:Select all the imported files and set Copy to output Directory : Copy always]


[Change the property of the XACT file("sound"), XACT FILES NEED TO BE COMPILED. Set the Build action to Compile]


After this run the game. The game will automatically compile the xact file to xgs format. The wavebank will be complied to xwb and the soundbank will be compiled to xsb.
Now we cleared all the conditions to use the sound manager class. 

GO TO YOUR Game1.cs, declare a soundManager at the top of the class.

 soundManager soundManager;

On our loadContent method, we need to set soundmanager as new soundmanager then load the content of the soundmanager class..

    soundManager = new soundManager(); 
    soundManager.loadcontent(this.Content ); // passes the Contentmanager of the game and loads the soundmanager class resources.
    soundManager.soundBank.PlayCue("BGM"); //PLAYS THE BGM CUE, the cues are made upon creating a xact file. Which means, you need to open the Xact file then click soundBank to see the cue names on it.

In this xact file that you downloaded, there are 4 cues i made.
"BGM" = background music.
"fire" = sound effect for firing bullets.
 "move" = sound effect for moving tanks.
"explosion" = sound effect to give impact to the explosion methods.


Using the fire cue -  goto to our fireBullets and fireAIBullets, add the line to play the fire cue whenever we fire a bullet..

 private void fireBullets()
        {
            if (player.numberOfBullets > 0)
            {
                gameObject bulletFire = new gameObject();
                bulletFire.alive = true;
                bulletFire.texture = Content.Load("bullet");
                bulletFire.rotation = player.rotation;
                bulletFire.velocity.X = (float)Math.Cos(bulletFire.rotation);
                bulletFire.velocity.Y = (float)Math.Sin(bulletFire.rotation);
                bulletFire.position = new Vector2(player.position.X + bulletFire.velocity.X * 100,
                    player.position.Y + bulletFire.velocity.Y * 100);
                bullet.Add(bulletFire);
                player.numberOfBullets--;
                soundManager.soundBank.PlayCue("fire");
            }

        }
        private void fireAIBullets()
        {
            if (enemy.numberOfBullets > 0)
            {
                gameObject bulletFire = new gameObject();
                bulletFire.alive = true;
                bulletFire.texture = Content.Load("bullet");
                bulletFire.rotation = enemy.rotation;
                bulletFire.velocity.X = (float)Math.Cos(bulletFire.rotation);
                bulletFire.velocity.Y = (float)Math.Sin(bulletFire.rotation);
                bulletFire.position = new Vector2(enemy.position.X + enemy.velocity.X * 100,
                    enemy.position.Y + bulletFire.velocity.Y * 100);
                bullet.Add(bulletFire);
                soundManager.soundBank.PlayCue("fire");
                enemy.numberOfBullets--;
            }

        }


Using the explosion cue - goto detect collision and play the explosion cue when collisions are detected
 private void detectCollisions(gameObject _bullets, gameObject _gameObject){
             Vector2 origin, origin1;
             origin = new Vector2(_bullets.texture.Width / 4, _bullets.texture.Height / 4);
             origin1 = new Vector2(_gameObject.texture.Width / 4, _gameObject.texture.Height / 4);
             BoundingBox bulletBounds = new BoundingBox();
             BoundingBox Player = new BoundingBox();
             Player.Min = new Vector3(_gameObject.position.X  - origin1 .X ,
                 _gameObject.position.Y - origin1.Y, 1f);
             Player.Max = new Vector3(origin1.X /2+ _gameObject .position .X ,
                 origin1.Y + _gameObject.position.Y, 1f);
             bulletBounds.Min = new Vector3(_bullets.position.X - origin.X  ,
                                 _bullets.position.Y-origin.Y , 1f);
             bulletBounds.Max = new Vector3(origin.X /2 + _bullets.position.X,
             origin.Y + _bullets.position.Y, 1f);
            if (_bullets.alive)
             {
                 if (_gameObject.alive)
                 {
                     if (Player.Intersects(bulletBounds))
                     {
                         _bullets.alive = false;
                         _gameObject.life -= 5;
                         soundManager.soundBank.PlayCue("explosion");
                         addExplosions(_bullets);
                     }
                 }
             }
         }

Using the move cue- go to your update method.
 if (currentKeyboardState.IsKeyDown(Keys.Up) && oldKeyboardState.IsKeyDown(Keys.Up))
                    {
                        player.position += player.velocity * moveSpeed;
                        player.position.X = MathHelper.Clamp(player.position.X, player.texture.Width / 4, GraphicsDevice.Viewport.Width - player.texture.Width / 4);
                        player.position.Y = MathHelper.Clamp(player.position.Y, player.texture.Height / 4, GraphicsDevice.Viewport.Height - player.texture.Height / 4);
                        soundManager.soundBank.PlayCue("move");
                    }
                    if (currentKeyboardState.IsKeyDown(Keys.Down) && oldKeyboardState.IsKeyDown(Keys.Down))
                    {

                        player.position -= player.velocity * moveSpeed;
                        player.position.X = MathHelper.Clamp(player.position.X, player.texture.Width / 4, GraphicsDevice.Viewport.Width - player.texture.Width / 4);
                        player.position.Y = MathHelper.Clamp(player.position.Y, player.texture.Height / 4, GraphicsDevice.Viewport.Height - player.texture.Height / 4);
     soundManager.soundBank.PlayCue("move");

                    }



ALSO PLAY MOVE CUE WHEN AI IS MOVING.

   private void AI(GameTime gameTime)
        {
            Random r = new Random();
            float x = player.position.X - enemy.position.X;
            float y = player.position.Y - enemy.position.Y;
            float desiredAngle = (float)Math.Atan2(y, x);
            enemy.rotation = desiredAngle;
            enemy.velocity.X = (float)Math.Cos(enemy.rotation);
            enemy.velocity.Y = (float)Math.Sin(enemy.rotation);
            if (gameTime.TotalGameTime .Seconds % 5 == 0)
            {         
                if (r.Next(1, 2) == 1)
                {

                    if (Vector2.Distance(enemy.position, player.position) > 150)
                    {
                        enemy.position += enemy.velocity * moveSpeed;
                        soundManager.soundBank.PlayCue("move");
                    }
                }
                else
                {
                    enemy.position -= enemy.velocity * moveSpeed;
                    soundManager.soundBank.PlayCue("move");
                }
            }
            
             if( gameTime .TotalGameTime  .Milliseconds % 500 == 0)
                fireAIBullets();
            
            enemy.position.X = MathHelper.Clamp(enemy.position.X, enemy.texture.Width / 4, GraphicsDevice.Viewport.Width - enemy.texture.Width / 4);
            enemy.position.Y = MathHelper.Clamp(enemy.position.Y, enemy.texture.Height / 4, GraphicsDevice.Viewport.Height - enemy.texture.Height / 4);

        }


NOW RUN THE GAME! MAKE SURE YOU ADDED ALL THE CODES IN THE RIGHT PLACE AND RIGHT TIME, ELSE YOU WILL GET AN ERROR.

Sunday, June 30, 2013

III. Using System input/output to get the files and folders in c#



Feeling bored and not motivated, i found myself watching my favorite anime "gintama". While watching I decided to code something just for passing time. I decided to write something about paint and files saving. In game development, saving file is important. You need to save scores, screenshots, equipment, game states , settings etc. There are many ways to read files in your computer. So let's start, create a new c# project , yes your right. We're going to use a console c# application..

Add System.IO in your packages..
using System.IO;

We can now use I/O packages in our console app..
What we wan't to do is to read a specific filepath / location and show all the files inside it..
Declare 2 arrays that will hold the name of folder and files in a directory.
Directory.Get will do the job for us. All we need to do is to assign the collected data into our string array. After that, use loops to write it in the console.


class Program
{
  static void Main(string[] args)
        {
            string[] files = Directory.GetFiles(@"C:\");
            string[] folders= Directory.GetDirectories(@"c:\");
            for (int x = 0; x < folders.Length; x++)
                Console.WriteLine(folders[x]);
            for (int x = 0; x < files.Length; x++)
                Console.WriteLine(files[x]);
            Console.ReadKey();
        }
}

execute the project





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.









II. Reading from a txt file. Lord of strings part II



As a programmer, you need to learn this too. There are many possible functions for getting data from a txt file. For example , you can use it to read dialogues and draw it in the game screen, reading game settings etc.

So create a new project and name it whatever you want.
The content we  need is a spritefont and a text file. Create a new spritefont and save it as font.

Copy and paste this to a new textFile, name it anim.txt


16
Year 1982 in Philippines |
" " |
The Country is currently ruled by the Spanish Empire.|
Jose Rizal, a physician, scholar, scientist, and writer founded the La Liga Filipina at Ilaya Street, Tondo Manila in 1982.|
La Liga Filipina is a progressive organization ought to build a new group sought |
to involve the people directly in the reform movement.|
July 6 1982 |
Dr. Jose Rizal was arrested and exiled because the La Liga Filipina became a threat to the Spanish Authorities.|
During the exile of Dr. Jose Rizal, The organization became inactive and soon to fall.|
With the efforts of Domingo Franco and Andres Bonifacio, |
the La Liga Filipina was reorganized and decided to support  La Solidaridad and the reforms it advocated.|
Eventually after some disarray in the leadership of the group, |
the Supreme Council of the League dissolved the society.|
The Liga membership split into two groups: |
the conservatives formed the Cuerpo de Compromisarios which pledged to continue supporting the La Solidaridad while |
the radicals led by Bonifacio devoted themselves to a new and secret society, the Katipunan.|

The first line of the text is the number of sentences. Import it to game content and copy the following properties.






The Using Statements:
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 System.IO;

We need to add the System.IO since we are going to use streamreader.
Next : Declaring Variables.
        SpriteFont font; 
        StreamReader sr; //Use a member of System.IO, enables us to read the contents of the file
        string[] line; //Array to store the sentences we read
        int  numberOfLines=0; // The number of sentences


At your load content method, declare and add the following lines and variables.


string fullPath = "the path of the txt file, see image below";
[Copy the full path generated by the game and paste it to the full path. Replace "\" by "/"]

string name ="anim.txt";

sr = new StreamReader(fullPath + name  ); //FIND THE FILE TO READ
numberOfLines = Int32.Parse(sr.ReadLine());// READ THE FIRST LINE TO GET THE No. of sentences

line=  sr.ReadToEnd().Split('|'); //read the txt file till the end, seperate each sentences when a '|' character is read.


And draw it into the screen, at your draw method..
  for (int x = numberOfLines; x > 0; x--) //set up a loop and read the lines until number of lines to read = 0
            {                      
               spriteBatch.DrawString(font, line[x], new Vector2(1, 20 * (x)), Color.White);
           }  
            spriteBatch.End();


RUN THE PROJECT



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;
using System.IO;
namespace sounds
{
  
    public class Game1 : Microsoft.Xna.Framework.Game
    {
        GraphicsDeviceManager graphics;
        SpriteBatch spriteBatch;
        SpriteFont font;
        StreamReader sr;
        string[] line;
        int  numberOfLines=0;


        public Game1()
        {
            graphics = new GraphicsDeviceManager(this);
            Content.RootDirectory = "Content";
        }

       
        protected override void Initialize()
        {
   

            base.Initialize();
        }

        protected override void LoadContent()
        {
            string fullPath = "D:/sounds/soundsContent/";
            string name ="anim.txt";
            spriteBatch = new SpriteBatch(GraphicsDevice);
            sr = new StreamReader(fullPath + name  );
            numberOfLines = Int32.Parse(sr.ReadLine());
           line=  sr.ReadToEnd().Split('|');

        }
        protected override void UnloadContent()
        {
         }

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

            spriteBatch.Begin();
            for (int x = numberOfLines; x > 0; x--)
            {
                                    
               spriteBatch.DrawString(font, line[x], new Vector2(1, 20 * (x)), Color.White);
              
           }  
        
            spriteBatch.End();
            base.Draw(gameTime);
        }
    }
}