2 Replies - 1655 Views - Last Post: 26 February 2012 - 02:22 PM

#1 gruffy  Icon User is offline

  • D.I.C Head

Reputation: 4
  • View blog
  • Posts: 106
  • Joined: 28-April 11

c# / XNA 4.0 - my projectiles wont fire one a time on button press

Posted 26 February 2012 - 11:01 AM

0 down vote favorite
share [g+] share [fb] share [tw]


thanks for reading. Problem: Upon spacebar press i need my projectile to fire and continue its life regardless of another press or letting go of the spacebar.

below is both the code adding, updating, and drawing the projectiles. I have tried numerous reworkings of this code but alas am not experienced enough to have found a suitable solution yet.

AddProjectile code below
//add projectile if spacebar is pressed

    private void AddProjectile(Vector2 position)
    {
        //i need somthing like this to make bullets autofire on phone
        //while (TouchPanel.IsGestureAvailable)
        //{
        //    Projectile projectile = new Projectile();
        //    projectile.Initialize(GraphicsDevice.Viewport, projectileTexture, position);
        //    projectiles.Add(projectile);
        //}

       if (currentKeyboardState.IsKeyDown(Keys.Space) ||
         currentGamePadState.Buttons.A == ButtonState.Pressed)
       {
           Projectile projectile = new Projectile();
           projectile.Initialize(GraphicsDevice.Viewport, projectileTexture, position);
           projectiles.Add(projectile);
       }
    }



Update Projectile code below
private void UpdateProjectiles()
    {
        //update projectiles
        for (int i = projectiles.Count - 1; i >= 0; i--)
        {

            if (currentKeyboardState.IsKeyDown(Keys.Space) ||
                currentGamePadState.Buttons.A == ButtonState.Pressed)
            {

               //adds particle to first projectile but not again until the next fire butotn press
                //particleEngine.EmitterLocation = new Vector2(projectiles[i].Position.X, projectiles[i].Position.Y);
                projectiles[i].Update();
                projectileOn = true;


            }
            //if projectiles not being fired remove them from the game screen 
            else
            {
                projectiles.RemoveAt(i);
            }



        }

    }



draw method for projectiles below
//draw the projectiles
                //***********************************************************
                 //using the if here allows control of projectiles to pass...
                 //...to the "currentstate of the spacebar (is pressed = fire)
                 /***/

                if (currentKeyboardState.IsKeyDown(Keys.Space) ||
                    currentGamePadState.Buttons.A == ButtonState.Pressed)
                {
                    for (int i = 0; i < projectiles.Count; i++)
                    {
                        projectiles[i].Draw(spriteBatch);

                    }
                }

                //remove projectiles and reset
                if (currentKeyboardState.IsKeyUp(Keys.Space) ||
                    currentGamePadState.Buttons.A == ButtonState.Released)
                {


                    UpdateProjectiles();
                }




So, this is what i have so far and as stated can get the projectile to worl fine , i just cant get them to continue their life (until a collision or they reach the end of screen) once i let go of the keyboard spacebar. Any help woud be greatly appreciated.
Thanks for reading once more. . gruffy :bananaman:
attached is the full game1.cs file if needed to get a better feel for the mess im in :)

Attached File(s)



Is This A Good Question/Topic? 0
  • +

Replies To: c# / XNA 4.0 - my projectiles wont fire one a time on button press

#2 Kilorn  Icon User is offline

  • XNArchitect
  • member icon



Reputation: 1356
  • View blog
  • Posts: 3,528
  • Joined: 03-May 10

Re: c# / XNA 4.0 - my projectiles wont fire one a time on button press

Posted 26 February 2012 - 01:30 PM

The reason they are disappearing once you release the space bar is because you have coded it that way. Inside the method for drawing projectiles, you've got the draw code inside of an if check which will only allow the code inside of it to execute if the conditions for the if are true. You'll want to take that if check out of there and have it just draw the projectiles without needing any sort of input.

Generally you'll want to have a method that creates the projectile and gives it a starting location and adding it to a list or array. This method will be called when the player presses the button to fire, which in your case is the space bar. In the Update(GameTime gameTime) method, you'll want to change the position of each projectile in the list or array depending on which direction it should be moving. Inside the draw method, you'll just simple loop through the list or array and draw any projectiles that are in there whether there is any sort of input at all.
Was This Post Helpful? 0
  • +
  • -

#3 gruffy  Icon User is offline

  • D.I.C Head

Reputation: 4
  • View blog
  • Posts: 106
  • Joined: 28-April 11

Re: c# / XNA 4.0 - my projectiles wont fire one a time on button press

Posted 26 February 2012 - 02:22 PM

hey kilorn,
thanks for your quick reply.
I have taken out the if but it has not changed my problem, though i can see where you are coming from when you said thats how i coded it to work, i had put that statement all ove rthe place just to get it to fire in the first instance.
Anyway, with regard to a method to construct the projectile i have a class :
Projectile.cs
//projectile.cs
//Usings

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;
// important uses required for WinPhone7 touch controls access
using Microsoft.Xna.Framework.Input.Touch;

namespace Shooter
{
    public class Projectile
    {
        //keyboard and game  state vars
        KeyboardState currentKeyboardState;
        KeyboardState previousKeyBoardState;


        //GamePadState currentGamepadState;
        //GamePadState previousGamepadState;
        /*public int Score
        {
            get { return Score);}
        }
       */

        //image representing the laser projectile
        public Texture2D Texture;

       // public Player player;

        //position of the projectile relative...
        //...to the upper left hand side of screen.
        public Vector2 Position;

        //state of the projectile
        public bool Active;

        //level of damage projectile can inflict on enemy
        public  int Damage;

        //represents the viewable boundry of game
        Viewport viewport;

        //get the width of the projectile ship
        public int Width
        {
            get { return Texture.Width; }
        }

        //get the height of the projectile ship
        public int Height
        {
            get { return Texture.Height; }
        }

        //determines hw fast the projectile moves.
        float projectileMoveSpeed;


        public void Initialize(Viewport viewport, Texture2D texture, Vector2 position)
        {
            Texture = texture;
            Position = position;
            this.viewport = viewport;

            Active = false;
            
                Damage = 2;
            
                projectileMoveSpeed = 10f;
            
            
            
        }

        public void Update()
        {
            
            //projectiles always move right
            Position.X += projectileMoveSpeed;

            //read the current keyboard and gamepad status  then store it
            currentKeyboardState = Keyboard.GetState();
            //currentGamePadState = GamePad.GetState(PlayerIndex.One);

            
            //RELATED TO VARS ABOVE public void initialize
            //if spacebar pressed then projectile is active
            //
            if (currentKeyboardState.IsKeyDown(Keys.Space))
            {
                
                Active = true;

                

            }


            //deactivate the bullet if it leaves game screen or keyboard state = false
            if (Position.X + Texture.Width / 2 > viewport.Width )
            {
                Active = false;

                //thought this might get rid of continued projectile from last pos, but it dont work !!!!
                //Texture.Equals(null); never use cos its crap !
                

            }


           
        }

        public void Draw(SpriteBatch spriteBatch)
        {
            
            spriteBatch.Draw(Texture, Position, null, Color.White, 0f,
                new Vector2(Width / 2, Height / 2), 1f, SpriteEffects.None, 0f);

        }



    }
}




So i am wondering if it is in here that i should be placing the update and draw code to create each instance of a projectile in the list.
Sorry for being a big ol noob at this , im learning as quick as i can , but sometimes these things just stump your brain when workingon the same thing for too long and im still a bit rubbish at programming (which can never be a help i guess).

below is my entire game1.cs class
as the full code in game1 may clarify where i am going wrong.....maybe

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;
// important uses required for WinPhone7 touch controls access
using Microsoft.Xna.Framework.Input.Touch;



namespace Shooter
{
    /// <summary>
    /// This is the main type for the game
    /// </summary>
    public class Game1 : Microsoft.Xna.Framework.Game
    {
        //create a GameState enumerator to employ a splashscreen between game states
        public enum GameState { START, PLAY, END}
        
        
        GameState currentGameState = GameState.START;

        public static int score;

        //particle effects vars
        private Texture2D blue;
        private Texture2D green;
        private Texture2D red;

        private float blueAngle = 0;
        private float greenAngle = 0;
        private float redAngle = 0;

        private float blueSpeed = 0.025f;
        private float greenSpeed = 0.017f;
        private float redSpeed = 0.022f;

        private float distance = 0f;



        ParticleEngine particleEngine;

        //end particle effects vars

        GraphicsDeviceManager graphics;
        SpriteBatch spriteBatch;

        //Represents player
        Player player;

        //add player health bar variable
        Texture2D healthBar;
        
        
        //keyboard states used to determine button presses
        KeyboardState currentKeyboardState;
        KeyboardState previousKeyboardState;

        // Gamepad states used to determine button presses
        GamePadState currentGamePadState;
        GamePadState previousGamePadState;

        // A movement speed for the player
        float playerMoveSpeed;

        //image used to display static background
        Texture2D mainBackground;

        //parallaxing layers
        parallaxingBackground bgLayer1;
        parallaxingBackground bgLayer2;
        parallaxingBackground bgLayer3;

        //enemies
        Texture2D enemyTexture;
        List<Enemy> enemies;

        //The rate at which enemies generate

        TimeSpan enemySpawnTime;
        TimeSpan previousSpawnTime;

        //a random number generator
        Random random;

        //image used for projectile(s)
        Texture2D projectileTexture;
        Texture2D projectileTexture2;

        //contsructor lists to hold projectiles for player and enemy
        List<Projectile> projectiles = new List<Projectile>();
        //List<Projectile> enemyProjectiles = new List<Projectile>();

        //active state of projectiles (not used yet)
         bool projectileOn;
        
        //the rate of player projectile fire
        TimeSpan fireTime;
        TimeSpan previousFireTime;

        //explosion animation
        Texture2D explosionTexture;
        List<Animation> explosions;

        //sound effect played when laser fired
        SoundEffect laserSound;

        //sound effect when player/ Enemy dies
        SoundEffect explosionSound;

        //music during gameplay
        Song gamePlayMusic;

        
        



        //font used to display UI elements
        SpriteFont font;
        //hold position data for font
        Vector2 textPosition;

        //add smoke texture 
        //Texture2D smokeTexture;

        //add list for smoke to generate in for animation
        //List<Vector2> smokeList = new List <Vector2>();
        //Random randomizer = new Random();


        public void ChangeGameState(GameState state, int level)
        {
            currentGameState = state;
            
        }

        //public game constructor
        //create game environment
        public Game1()
        {
            graphics = new GraphicsDeviceManager(this);
            //graphics.PreferredBackBufferWidth = 800;
            //graphics.PreferredBackBufferHeight = 480;
            Content.RootDirectory = "Content";
            //default to wp7 frame rate 30fps
           // TargetElapsedTime = TimeSpan.FromTicks(333333);
            //extend battery life while game running
           // InactiveSleepTime = TimeSpan.FromSeconds(1);
        }

        /// <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.
        

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


            //Initialize background layer objects
            bgLayer1 = new parallaxingBackground();
            bgLayer2 = new parallaxingBackground();
            bgLayer3 = new parallaxingBackground();

            
          
            // Initialize a new player class object
            player = new Player();

            //set a constant player move speed using float value
            playerMoveSpeed = 8.0f;

            //Enable "FreeDrag" gesture
            TouchPanel.EnabledGestures = GestureType.FreeDrag;
            

            //initialize the enemies list 
            enemies = new List<Enemy>();

            //set the time keeping to zero
            previousSpawnTime = TimeSpan.Zero;

            //used to determine how fast enemies should respawn
            enemySpawnTime = TimeSpan.FromSeconds(.5f);

            //initialize random number gen
            random = new Random();

            //initialize projectile data
           // int playerElapsedTime = 0;
            //int playerFireRate = 250;

            projectiles = new List<Projectile>();
            projectileOn = false;
            
            //Texture2D projectileTexture;
           

            //set the fire rate
            fireTime = TimeSpan.FromSeconds(.5f);

            //initialize explosions 
            explosions = new List<Animation>();

            //Initialize player score
            score = 0;
            

            

            //initialize smoke texture
           // smokeTexture = Content.Load<Texture2D>("smoke");


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

            // TODO: use this.Content to load your game content here
            //heaLTHBAR
            healthBar = Content.Load<Texture2D>("healthBar") as Texture2D;
            //particles
            List<Texture2D> textures = new List<Texture2D>();
            textures.Add(Content.Load<Texture2D>("smoke"));
            textures.Add(Content.Load<Texture2D>("star2"));
            textures.Add(Content.Load<Texture2D>("circle2"));

            particleEngine = new ParticleEngine(textures, new Vector2(400, 240));



            //Load player resources
            Animation playerAnimation = new Animation();
            Texture2D playerTexture = Content.Load<Texture2D>("shipAnimation");
            playerAnimation.Initialize(playerTexture, Vector2.Zero, 115, 69, 8, 30, Color.White, 1f, true);

            Vector2 playerPosition = new Vector2(GraphicsDevice.Viewport.TitleSafeArea.X, GraphicsDevice.Viewport.TitleSafeArea.Y + GraphicsDevice.Viewport.TitleSafeArea.Height / 2);
            player.Initialize(playerAnimation, playerPosition);

            //load the parallaxing background
            bgLayer1.Initialize(Content, "layer3_offset", GraphicsDevice.Viewport.Width, - 1);
            bgLayer2.Initialize(Content, "layer2_offset", GraphicsDevice.Viewport.Width, -2);
            bgLayer3.Initialize(Content, "layer1_offset", GraphicsDevice.Viewport.Width, -2);

            //load enemy animation/texture into game envronment (current pos above player)
            enemyTexture = Content.Load<Texture2D>("mineAnimation");

            //load the projectile (current pos above enemy)
            projectileTexture = Content.Load<Texture2D>("laser");
            //load the different colours
            //load the projectile (current pos above enemy)
            projectileTexture2 = Content.Load<Texture2D>("laser1000");
            //load the projectile (current pos above enemy)
           // projectileTexture3 = Content.Load<Texture2D>("laser5000");
            //load the projectile (current pos above enemy)
           // projectileTexture4 = Content.Load<Texture2D>("laser10000");
            //load the projectile (current pos above enemy)
           // projectileTexture5 = Content.Load<Texture2D>("laser20000");

            //load the explosion (current pos above projectile)
            explosionTexture = Content.Load<Texture2D>("explosion");

            //load gameplay music
           // gamePlayMusic = Content.Load<Song>("Sound/gameMusic");

            //load laser & explosion sound effect
            //laserSound = Content.Load<SoundEffect>("sound/laserFire");
            //explosionSound = Content.Load<SoundEffect>("sound/explosion");

            //load score font
            font = Content.Load<SpriteFont>("gameFont");

            //start music at game start
            //PlayMusic(gamePlayMusic);

            //load rgb particle color content
            blue = Content.Load<Texture2D>("blue");
            green = Content.Load<Texture2D>("green");
            red = Content.Load<Texture2D>("red");

            //load in the background main image
            mainBackground = Content.Load<Texture2D>("level2bgII");

            
        }

        /// <summary>
        /// UnloadContent will be called once per game and is the place to unload
        /// all content
        /// </summary>
        protected override void UnloadContent()
        {
            // TODO: Unload any non ContentManager content here
        }

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

            //only perfom an action based on current game state
            switch (currentGameState)
            {
                case GameState.START:
                    break;
                case GameState.PLAY:
                    break;
                case GameState.END:
                    break;
            }//end switch

            // Allows the game to exit using gamepad or keyboard
            if (Keyboard.GetState(PlayerIndex.One).IsKeyDown(Keys.Escape)||
                GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
                this.Exit();


            // save previous state of the keyboard and gamepad to determine single keyboard/button presses
            previousGamePadState = currentGamePadState;
            previousKeyboardState = currentKeyboardState;

            //read the current keyboard and gamepad status  then store it
            currentKeyboardState = Keyboard.GetState();
            currentGamePadState = GamePad.GetState(PlayerIndex.One);

            //call the UpdatePlayer method to renew position of player sprite
            UpdatePlayer(gameTime);

            //update the parallaxing background
            bgLayer1.Update();
            bgLayer2.Update();
            bgLayer3.Update();

            //update enemies
            UpdateEnemies(gameTime);

            //update collision
            UpdateCollision();

            //update the projectiles
            UpdateProjectiles();

            //update explosions
            UpdateExplosions(gameTime);

            //update particle engine
            
            particleEngine.Update();

            //update large rgb color particle angles
            blueAngle += blueSpeed;
            greenAngle += greenSpeed;
            redAngle += redSpeed;


            base.Update(gameTime);
        }//end of Update method

        private void AddEnemy()
        {
            //create animation object
            Animation enemyAnimation = new Animation();

            //initialize correct positioning for animation to start
            //showing vector position at, width 75 height 20, 8 rows of and 1 col
            enemyAnimation.Initialize(enemyTexture, Vector2.Zero, 115, 60, 8, 0, Color.White, 1f, true);

            //randomly generate enemy positions
            Vector2 position = new Vector2(GraphicsDevice.Viewport.Width + enemyTexture.Width / 2,
                                            random.Next(100, GraphicsDevice.Viewport.Height - 20));
        
            
            //create an ememy
            Enemy enemy = new Enemy();

            //Initialize the enemy
            enemy.Initialize(enemyAnimation, position);

            //add enemy to the active enemies list
            enemies.Add(enemy);
        }

        //add projectile if spacebar is pressed
        //can this become a switch case and have the phone defined if not xbox or pc????i dunno yet 

/*
         public void UpdateBulletList(List<Bullet> bulletList, double elapsedTime)
        {
            bulletList.ForEach(x => x.Update(elapsedTime));
            CheckOutOfBounds(_bullets);
            RemoveDeadBullets(bulletList);
        }
*/
        private void AddProjectile(Vector2 position)
        {
/*
 * i need somthing like this to make bullets autofire on phone  
 * while (TouchPanel.IsGestureAvailable)   
 * {   
 * Projectile projectile = new Projectile();  
 * projectile.Initialize(GraphicsDevice.Viewport, projectileTexture, position);   
 * projectiles.Add(projectile); 
 * }
*/
            if (currentKeyboardState.IsKeyDown(Keys.Space) ||
                            currentGamePadState.Buttons.A == ButtonState.Pressed)
            {
                //construct projectile object 
                Projectile projectile = new Projectile();
                projectile.Initialize(GraphicsDevice.Viewport, projectileTexture, position);
                projectiles.Add(projectile);
            }
            
        }






        private void AddExplosion(Vector2 position)
        {
            Animation explosion = new Animation();
            explosion.Initialize(explosionTexture, position, 134, 134, 12, 45, Color.White,
                1f, false);
            explosions.Add(explosion);
        }

        
        // here is an new class that encapsulates all the work needed to update the player position
        // this will be called within the update method
        //this approach keeps is encapsulation and helps keep the many methods used during update to stay tidy and easily..
        //editable without looking at one long method inside private void Update() above
        private void UpdatePlayer(GameTime gameTime)
        {
            //allows the passing of timing from game loops Update() method into Player.class so it can be passed onto the Animation.class(oo baby)
            player.Update(gameTime);

            //player.Position.X/Y denotes the current position of the player...
            //the emitter will update and check for new position and emit at those current coords.
            //
            particleEngine.EmitterLocation = new Vector2(player.Position.X - 10, player.Position.Y);


            //phone controls for winphone7
            while (TouchPanel.IsGestureAvailable)
            {
                GestureSample gesture = TouchPanel.ReadGesture();
                if (gesture.GestureType == GestureType.FreeDrag)
                {
                    player.Position += gesture.Delta;
                }
            }


            //get thumbstick controls from xbox 360 controller
            player.Position.X += currentGamePadState.ThumbSticks.Left.X * playerMoveSpeed;
            player.Position.Y -= currentGamePadState.ThumbSticks.Left.Y * playerMoveSpeed;



            //use the Keyboard or d-Pad(xbox360 ccontroller)
            //stage one - capture left
            if (currentKeyboardState.IsKeyDown(Keys.A) || currentKeyboardState.IsKeyDown(Keys.Left) ||
                        currentGamePadState.DPad.Left == ButtonState.Pressed)
            {
                player.Position.X -= playerMoveSpeed;
            }
            //stage two - capture right
            if (currentKeyboardState.IsKeyDown(Keys.D) || currentKeyboardState.IsKeyDown(Keys.Right) ||
                        currentGamePadState.DPad.Right == ButtonState.Pressed)
            {
                player.Position.X += playerMoveSpeed;
            }
            // stage three - capture up
            if (currentKeyboardState.IsKeyDown(Keys.W) || currentKeyboardState.IsKeyDown(Keys.Up) ||
                        currentGamePadState.DPad.Up == ButtonState.Pressed)
            {
                player.Position.Y -= playerMoveSpeed;

            }
            //stage four - capture down
            if (currentKeyboardState.IsKeyDown(Keys.S) || currentKeyboardState.IsKeyDown(Keys.Down) ||
                        currentGamePadState.DPad.Down == ButtonState.Pressed)
            {
                player.Position.Y += playerMoveSpeed;
            }



            if (currentKeyboardState.IsKeyDown(Keys.Space))
            {
                if ((int)gameTime.ElapsedGameTime.TotalMilliseconds > fireTime.Milliseconds)
                {
                    //time = 0;
                   // GameObject tempObj = new GameObject();
                    //tempObj.sprite = new projectileTexture;
                    //tempObj.rect = new Rectangle(player.rect.X + 64, player.rect.Y + 24, 16, 16);
                    //tempObj.speed = 5;
                    //tempObj.active = true;
                    //playerBulletList.Add(tempObj);
                }



                //ensure player object does not exceed screen boundaries
                player.Position.X = MathHelper.Clamp(player.Position.X, 0, GraphicsDevice.Viewport.Width - player.Width);
                player.Position.Y = MathHelper.Clamp(player.Position.Y, 0, GraphicsDevice.Viewport.Height - 10);

                //fire every interval set as the fireTime.
                if (currentKeyboardState.IsKeyDown(Keys.Space))
                {
                    //reset  current time
                    previousFireTime = gameTime.TotalGameTime;

                    //add projectile, but add it to the front and centre of player
                    AddProjectile(player.Position + new Vector2(player.Width / 2, 0));
                    //Active = true;

                    //playing laser sound was here



                }



                //possible better way ....
                //...foreach score of (1000) projectileTexture change texture

                //if score greater than 1000, power up (for now change projectile texture)
                if (score > 1000 && player.Health >= 50)
                {

                    projectileTexture = projectileTexture2;


                }

                //reset score to zero and exit game upon player player death...
                //-1 allows the player health to drop by a further  10 giving 0 as the last life amount...
                //before next hit

                if (player.Health <= -1)
                {

                    player.Health = 100;
                    score = 0;
                    this.Exit();
                }

            }
        }
        //end of Update Player() method

       

        private void UpdateEnemies(GameTime gameTime)
        {
            
            //Spawn new enemies every 0.5secs (half a second)
            if (gameTime.TotalGameTime - previousSpawnTime > enemySpawnTime)
            {
                previousSpawnTime = gameTime.TotalGameTime;

                //add an enemy
                AddEnemy();
            }

            //Update the enemies
            for (int i = enemies.Count - 1; i >= 0; i--)
            {
                enemies[i].update(gameTime);
                

                if (enemies[i].Active == false)
                {
                    //if not active and health <= 0
                    if (enemies[i].Health <= 0)
                    {
                        //add explosion
                        AddExplosion(enemies[i].Position);
                        particleEngine.EmitterLocation = new Vector2(enemies[i].Position.X, enemies[i].Position.Y);

                        /*temporarily removed*/
                        //play explosion sound
                        //explosionSound.Play();

                        //scor add was ere


                        
                        //add to player score on enemy hit/collision
                            score += enemies[i].Value;
                       
 
                    }
                    
                    enemies.RemoveAt(i);
                   
                    
                    
                }
            }
        }

        private void UpdateCollision()
        {
            //use the rectangle`s built in  intersect function to...
            //...determine if two object are overlapping

            Rectangle rectangle1;
            Rectangle rectangle2;
            
            

            //only create the rect once fro the player
            rectangle1 = new Rectangle((int)player.Position.X,
            (int)player.Position.Y,
            player.Width - 15,
            player.Height - 10);
            //the - numbers help reduce the bounding box of the rectangle to make collisions seem 
            //a little more realistic

            
            

            //calculate collision between the player and enemies
            for (int i = 0; i < enemies.Count; i++)
            {
                rectangle2 = new Rectangle((int)enemies[i].Position.X,
                    (int)enemies[i].Position.Y,
                    enemies[i].Width,
                    enemies[i].Height);

                //determine if player and enemy collide
                if (rectangle1.Intersects(rectangle2))
                    {
                        //subtract health from player
                        player.Health -= enemies[i].Damage;

                        

                        projectileTexture2 = projectileTexture;
                        

                        //destroy enemy due to collision
                        enemies[i].Health = 0;

                        //if player health depleted destroy player
                        if (player.Health <= 0)
                            
                            player.Active = false;


                        
                            
                    }
               
               
                
             }

            //Ship particle emission vs enemy collision to do

            
            
            //projectile vs Enemy Collision
            for (int i = 0; i < projectiles.Count; i++)
            {
                for (int j = 0; j < enemies.Count; j++)
                {
                    //create rectangles needed to determine player/enemy collisions.
                    rectangle1 = new Rectangle((int)projectiles[i].Position.X - projectiles[i].Width / 2,
                    (int)projectiles[i].Position.Y - projectiles[i].Height / 2,
                    projectiles[i].Width, projectiles[i].Height);

                    rectangle2 = new Rectangle((int)enemies[j].Position.X - enemies[j].Width / 2,
                    (int)enemies[j].Position.Y - enemies[j].Height / 2,
                    enemies[j].Width, enemies[j].Height);

                    //determine if the two objects collided with each other
                    if (rectangle1.Intersects(rectangle2))
                    {
                        enemies[j].Health -= projectiles[i].Damage;
                        projectiles[i].Active = false;
                    }
                }
            }
      }

        private void UpdateProjectiles()
        {
            ////update projectiles
            ////
            for (int i = projectiles.Count - 1; i >= 0; i--)
            {

                if (currentKeyboardState.IsKeyDown(Keys.Space) ||
                      currentGamePadState.Buttons.A == ButtonState.Pressed)
                {

                    //if (TargetElapsedTime > fireTime)
                    //{
                    //    TargetElapsedTime = 0;
                    //    Projectile projectile = new Projectile();

                    //}
                    //adds particle to first projectile but not again until the next fire butotn press
                    //particleEngine.EmitterLocation = new Vector2(projectiles[i].Position.X, projectiles[i].Position.Y);
                    //INTERESTINGLY , TAKE THESE OUT AND THE LASER STILL WORKS BUT WITH WEIRD SIDE EFFECT
                    projectiles[i].Update();
                    projectileOn = true;


                }
                //if projectiles not being fired remove them from the game screen 
                else
                {
                    projectiles.RemoveAt(i);
                }
            
           //for (int i =  projectiles.Count - 1; i >= 0; i--)
           //{
           //     if (projectiles[i].Active)
           //     {

           //     }
           //}
                
            }

        }

        //this to go above to add smoke
        //update smoke with projectile position
        //for (int k = 0; k < 5; k++ )
        //{
        //    Vector2 smokePos = projectiles[i].Position;
        //    smokePos.X += randomizer.Next(10) - 5;
        //    smokePos.Y += randomizer.Next(10) - 5;
        //    smokeList.Add(smokePos);
        //}

       
        //  private void DrawSmoke()
        // {
        
        //    foreach (Vector2 smokePos in smokeList)
        //        spriteBatch.Draw (smokeTexture, smokePos, null,
        //           Color.White, 0, new Vector2(40, 35),0.2f, SpriteEffects.None, 1 );
        // }
         

        private void UpdateExplosions(GameTime gameTime)
        {
            for (int i = explosions.Count - 1; i >= 0; i--)
            {
                explosions[i].Update(gameTime);
                    if (explosions[i].Active == false)
                    {
                        explosions.RemoveAt(i);
                    }
            }
        }

       
        
        /// 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)
        {
            
                //only draw certain items based on current gamestate
            //switch (currentGameState)
            //{
                    //start screen
                //case GameState.START:
                        //GraphicsDevice.Clear(Color.AliceBlue);
                        //spriteBatch.Begin();
                        //string text = "The Last Human";
                    //spriteBatch.DrawString (text), new Vector2 ((window.ClientBounds.Width / 2), (window.ClientBounds.Height / 2)), Color.SaddleBrown;


                    //break;

                //during game play 
                //case GameState.PLAY:
                    GraphicsDevice.Clear(Color.CornflowerBlue);

                    // TODO: Add your drawing code here for during ingame play

                        //particle movement, rotation and blend 
                        //red, blue green colors, math math math 
                        distance = ((player.Position.X) - 500);



                        Vector2 bluePosition = new Vector2(
                        (float)Math.Tan(blueAngle) * (distance),
                        (float)Math.Sin(blueAngle) * distance);
                        Vector2 greenPosition = new Vector2(
                                        (float)Math.Tan(greenAngle) * (distance / 2),
                                        (float)Math.Cos(greenAngle) *- distance);
                        Vector2 redPosition = new Vector2(
                                        (float)Math.Cos(redAngle) * (distance / 4),
                                        (float)Math.Tan(redAngle) *- distance);

                        Vector2 center = new Vector2(player.Position.X + player.Position.Y);
          
            
                    //start drawing
                    spriteBatch.Begin();

                    //the positioning here is VITAL  to the outcome of the level at which each spriteBatch object is drawn
                    //the player.Draw(); method instantiates the player sprite, and here i have chosen to sandwich it...
                    //between the 1st and 2nd bgLayers, this has made the ship feel more like its in the clouds.
                    //(*personal note*) the planting of the player ship inbetween the cloud layers offers....
                    //....opportunity to add relevant damages to ship for breach of cloud perimeters, maybe.(to be done in player.class)
           
            
                    //draw the background first
                    spriteBatch.Draw(mainBackground, Vector2.Zero, Color.White);

                    //next draw 1st scrolling layer above background
                    bgLayer1.Draw(spriteBatch);
            
                    //end current spritebatch draw set to allow for...
                    //placement of particle system behind player 
                    spriteBatch.End();
                    




                    //place particles behind player
                    particleEngine.Draw(spriteBatch);


                    //draw large color particles
                    spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.Additive);

                    spriteBatch.Draw(blue, center + bluePosition, Color.White);
                    spriteBatch.Draw(green, center + greenPosition, Color.White);
                    spriteBatch.Draw(red, center + redPosition, Color.White);
                    spriteBatch.End();
                    //end draw large color particles above other particle emitter...
                    //and below player ship




                    //place particles behind player
                    particleEngine.Draw(spriteBatch);

                    //continue to draw remaining sprite elements
                    spriteBatch.Begin();

                   

                    //draw the player
                    player.Draw(spriteBatch);

                    //draw enemies
                    for (int i = 0; i < enemies.Count; i++)
                    {
                        enemies[i].Draw(spriteBatch);
                    }

                    //next draw 2nd scrolling layer above player 
                    bgLayer2.Draw(spriteBatch);

                    //spriteBatch.Begin();
                    //draw healthBar
                    spriteBatch.Draw(healthBar, new Rectangle(this.window.ClientBounds.Width / 2 - healthBar.Width / 2,
                        30, healthBar.Width, 44), new Rectangle(0, 45, healthBar.Width, 44), Color.Green);



                    //draw surroundinding box
                    spriteBatch.Draw(healthBar, new Rectangle(this.window.ClientBounds.Width / 2 - healthBar.Width / 2,
                        30, healthBar.Width, 44), new Rectangle(0, 0, healthBar.Width, 44), Color.White);

                    //Draw curent health in healthBar
                    spriteBatch.Draw(healthBar, new Rectangle(this.window.ClientBounds.Width / 2 - healthBar.Width / 2,
                        30, (int)(healthBar.Width * ((double)player.Health / 100)), 44),
                        new Rectangle(0, 45, healthBar.Width, 44), Color.AliceBlue);

                    //spriteBatch.End();
            
                     //draw the projectiles
                    //***********************************************************


                        for (int i = 0; i < projectiles.Count; i++)
                        {
                          projectiles[i].Draw(spriteBatch);

                        }


                        //remove projectiles and reset
                        if (currentKeyboardState.IsKeyUp(Keys.Space) ||
                            currentGamePadState.Buttons.A == ButtonState.Released)
                        {


                            UpdateProjectiles();
                        }


            
            

                    //draw smoke
                    //DrawSmoke();


                    //draw explosions
                    for (int i = 0; i < explosions.Count; i++)
                    {
                        explosions[i].Draw(spriteBatch);
                    }
                   

                    //draw scores
            /*This draw a simple font and then copies it and moves 3 on both x & y axis, and changes colour*/
                    Vector2 drawPosition = textPosition;
                    spriteBatch.DrawString(font, "ISK:  " + score, drawPosition, Color.Gray);

                    drawPosition.X = drawPosition.X + 3;
                    drawPosition.Y = drawPosition.Y + 3;

                    spriteBatch.DrawString(font, "ISK:  " + score, drawPosition, Color.White);
            /*This way offers a  scrolling marqee*/
                    
                   
            
                    /*This place the simple font through spriteFont onto screen, what is shown is inside "speech marks"*/
                    //spriteBatch.DrawString(font, "ISK " + score, new Vector2
                    //    (GraphicsDevice.Viewport.TitleSafeArea.X, GraphicsDevice.Viewport.TitleSafeArea.Y),
                    //    Color.White);
                    //draw the player health status
                    //spriteBatch.DrawString(font, "DRAVIN " + player.Health, new Vector2
                    //    (GraphicsDevice.Viewport.TitleSafeArea.X, GraphicsDevice.Viewport.TitleSafeArea.Y + 30),
                    //    Color.White);




            //stop drawing
            spriteBatch.End();
            //break;

                //case GameState.END:
            //break;

            //}

            

            base.Draw(gameTime);
        }

        //private void PlayMusic(Song song)
        //{
        //    //due to way mediaplayer plays music
        //    //we have to catch the exception. Music willl play when...
        //    //game is not tethered.
        //    try
        //    {
        //        //Play music
        //        MediaPlayer.Play(song);

        //        //loop the current track
        //        MediaPlayer.IsRepeating = true;
        //    }
        //    catch { }
        //}
    }
}



Thanks for reading
Gruffy :) :bananaman:
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1