Friday, June 28, 2013

V. Plane Game?? Shooting Projectiles against enemies



Create a new project, name it chapter 2.

Project Files: save and import to game..

[save as bullet]

[save as plane]

[save as enemy]

Before we proceed, let's set up the game..
let's say the plane can only fire 1 bullet at a time..
 int noOfbullet =1;
Declare the speed,texture,velocity and position variables for the game objects..


Texture2D bullet, plane;
Vector2 bulletPosition, planePosition;
float bulletSpeed = 5f;
//Declare Keyboardstates for input handling
KeyboardState currentKeyboardState,oldKeyboardState;
      bool bulletIsAlive = false;

At loadContent
bullet = Content.Load<Texture2D>("bullet");
plane = Content.Load<Texture2D>("plane");
planePosition = new Vector2(GraphicsDevice.Viewport.Width /2 - plane.Width /2, GraphicsDevice.Viewport.Height - 50- plane.Height);
Set the plane position at the lower middle part of the screen.



At the Update Method

set up the input handler
            currentKeyboardState = Keyboard.GetState();
           if (currentKeyboardState.IsKeyDown(Keys.Right) && oldKeyboardState.IsKeyDown(Keys.Right))
                {
                    planePosition .X += 10;
                }
                if (currentKeyboardState.IsKeyDown(Keys.Left) && oldKeyboardState.IsKeyDown(Keys.Left))
                {
                    planePosition .X -= 10;
                }
          oldKeyboardState = currentKeyboardState;

At the Draw Method, draw the plane..

spriteBatch.Begin();
spriteBatch.Draw(plane,planePosition,Color.White);
spriteBatch.End();


RUN THE GAME



Create a method for bulletUpdate..
 public void updateBullet()


        {
//IF THE BULLET IS ALIVE UPDATE IT AND DRAW IT
            if (bulletIsAlive)
            {
              
                bulletVelocity = new Vector2(0, bulletSpeed);
                bulletPosition.Y -= bulletVelocity.Y;
                spriteBatch.Draw(bullet, bulletPosition, Color.White);
                
//IF THE BULLET IS LESS THAN TO ZERO OR OUT OF BOUNDS KILL THE BULLET SO IT WONT UPDATE
               if (bulletPosition.Y < 0)
                {
                    bulletIsAlive = false;
                    noOfbullet++;
                }

            }

        }
        public void fireBullet()
        {
// IF THE NUMBER OF BULLET IS EQUAL OR GREATER THAN 1 , FIRE THE BULLET
            if (noOfbullet >= 1)
            {
                bulletIsAlive = true; //MAKE IT ALIVE SO IT WILL UPDATE
                noOfbullet--;  //SUBTRACT THE 1 from the no of Bullet
                bulletPosition = new Vector2(planePosition.X + plane.Width / 2 - bullet.Width / 2,
              planePosition.Y); //SET THE POSITION OF THE BULLER ON FIRE

            }
        }

ADD the updateBullet method in the draw method..

            spriteBatch.Begin();
            spriteBatch.Draw(plane, planePosition, Color.White);
            updateBullet();
            spriteBatch.End();


ADD the fireBullet to the update method..

    if (currentKeyboardState.IsKeyDown(Keys.Space) && oldKeyboardState.IsKeyDown(Keys.Space))
            {
                fireBullet(); // IF SPACE IS PRESSED FIRE A BULLET
            }




[RUN THE GAME AND FIRE A BULLET]

Now we're going to set up the enemy..
At the bottom of your  public Game1 class, create a new class.

 class enemy{
        public Vector2 position;
        public bool alive;
        public Texture2D texture;
        public enemy()
        {
        }
}

This will hold the values of enemies..

Then after your game1 class, where you declare variables. Declare a new list of enemies and the enemy number..

 List<enemy> enemyList = new List<enemy>();
 const int enemyNumber = 5;


At your load content , set up the enemy and add it to the enemy list depending on its number..

      for (int x = 0; x <= enemyNumber; x++)
            {
                int y = 0; //set the y position
                enemy n = new enemy(); //create a new enemy
                n.texture = Content.Load<Texture2D>("enemy"); // set the current texture of enemy
                n.alive = true; //set the enemy alive 
                n.position = new Vector2(x* 120 , y); //set the position of the enemy
                enemyList.Add(n); //add the new enemy to the list of enemies
            }

On your Draw Method...
Add the following lines..

  foreach (enemy enemy in enemyList) //FOREACH ENEMY IN THE ENEMELIST
  {
       if (enemy.alive) //IF THE ENEMY IS ALIVE DRAW IT
       {
                    spriteBatch.Draw(enemy.texture, enemy.position, Color.White);
       }
}

[NOW RUN THE GAME]



Next create a collision detection...
The method will check 1 enemy..
  private void updateEnemies(enemy enemy)
        {
            if (enemy.alive) //IF THE ENEMY IS ALIVE CHECK THE POSITION OF BULLET AND ENEMY
            {
                if (bulletPosition.X >= enemy.position.X
                    && bulletPosition.X <= enemy.position.X + enemy.texture.Width
                    && bulletPosition .Y > enemy .position .Y
                    && bulletPosition.Y < enemy.position.Y + enemy.texture.Height)
                    //CHECK THE BOUNDS OF ENEMY AND BULLET
                {
                    enemy.alive = false; //IF THE BULLET HITS THE ENEMY KILL ENEMY
                    bulletIsAlive = false; //KILL THE BULLET
                    noOfbullet++; //ADD 1 BULLET
                }

            }
        }
Now we have the updateEnemies method, we need to place a foreach loop in the Update method that will loop all the enemies in the enemylist and update it by using updateEnemies

foreach (enemy enemy in enemyList)
            {
                updateEnemies(enemy); //pass the enemy into the updateEnemy Method
            }

We're almost done, feel free to edit the source code whatever event you want to take place at the end of the game..



[Challenge : create a method that will update the position or behavior of the enemies..]


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 chapter2
{
   
    public class Game1 : Microsoft.Xna.Framework.Game
    {
        GraphicsDeviceManager graphics;
        SpriteBatch spriteBatch;
        Texture2D bullet, plane;
        Vector2 bulletPosition, planePosition;
        float bulletSpeed = 5f;
        int noOfbullet = 1;
        KeyboardState currentKeyboardState, oldKeyboardState;
        bool bulletIsAlive = false;
        Vector2 bulletVelocity = Vector2.Zero;
        List enemyList = new List();
        const int enemyNumber = 5;
        public Game1()
        {
            graphics = new GraphicsDeviceManager(this);
            Content.RootDirectory = "Content";
        }
        protected override void Initialize()
        {
            base.Initialize();
        }

        protected override void LoadContent()
        {
            spriteBatch = new SpriteBatch(GraphicsDevice);
            bullet = Content.Load("bullet");
            plane = Content.Load("plane");
            planePosition = new Vector2(GraphicsDevice.Viewport.Width / 2 - plane.Width / 2, GraphicsDevice.Viewport.Height - 50 -plane.Height);

            for (int x = 0; x <= enemyNumber; x++)
            {
                int y = 0;
                enemy n = new enemy();
                n.texture = Content.Load("enemy");
                n.alive = true;
               
                n.position = new Vector2(x* 120 , y);
                enemyList.Add(n);
                
            }
        }

        protected override void UnloadContent()
        {

        }

        protected override void Update(GameTime gameTime)
        {
            currentKeyboardState = Keyboard.GetState();
            if (currentKeyboardState.IsKeyDown(Keys.Right) && oldKeyboardState.IsKeyDown(Keys.Right))
            {
                planePosition.X += 10;
            }
            if (currentKeyboardState.IsKeyDown(Keys.Left) && oldKeyboardState.IsKeyDown(Keys.Left))
            {
                planePosition.X -= 10;
            }
            if (currentKeyboardState.IsKeyDown(Keys.Space) && oldKeyboardState.IsKeyDown(Keys.Space))
            {
                fireBullet();
            }
            foreach (enemy enemy in enemyList)
            {
                updateEnemies(enemy);
            }
            oldKeyboardState = currentKeyboardState;
            base.Update(gameTime);
        }

        public void updateBullet()
        {
            if (bulletIsAlive)
            {
              
                bulletVelocity = new Vector2(0, bulletSpeed);
                bulletPosition.Y -= bulletVelocity.Y;
                spriteBatch.Draw(bullet, bulletPosition, Color.White);
                if (bulletPosition.Y < 0)
                {
                    bulletIsAlive = false;
                    noOfbullet++;
                }

            }

        }
        public void fireBullet()
        {
            if (noOfbullet >= 1)
            {
                bulletIsAlive = true;
                noOfbullet--;
                bulletPosition = new Vector2(planePosition.X + plane.Width / 2 - bullet.Width / 2,
              planePosition.Y);
              
            }
        }
        private void updateEnemies(enemy enemy)
        {
            if (enemy.alive)
            {
                if (bulletPosition.X >= enemy.position.X
                    && bulletPosition.X <= enemy.position.X + enemy.texture.Width
                    && bulletPosition .Y > enemy .position .Y
                    && bulletPosition.Y < enemy.position.Y + enemy.texture.Height)
                    
                {
                    enemy.alive = false;
                    bulletIsAlive = false;
                    noOfbullet++;
                }

            }
        }
        protected override void Draw(GameTime gameTime)
        {
            GraphicsDevice.Clear(Color.CornflowerBlue);
            spriteBatch.Begin();
            spriteBatch.Draw(plane, planePosition, Color.White);
            foreach (enemy enemy in enemyList)
            {
                if (enemy.alive)
                {
                    spriteBatch.Draw(enemy.texture, enemy.position, Color.White);
                }

            }
            updateBullet();
            spriteBatch.End();
            base.Draw(gameTime);
        }
    }
    class enemy{
        public Vector2 position;
        public bool alive;
        public Texture2D texture;
        public enemy()
        { 
        }
    }
}