3 Replies - 1370 Views - Last Post: 06 October 2012 - 02:46 PM

#1 mxa92  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 11
  • Joined: 22-November 11

Getting spaceship to fire (Space Invaders 'clone')

Posted 03 October 2012 - 06:38 PM

I've spent days playing around with my code and reading/watching tutorials and nothing seems to work :/

I have a sprite class (which contains general sprite information) and a player class (Which has all of the information for the spaceship), and am needing to create a bullet class as both the player and invaders are going to be able to inherit from it.

At the moment no bullet sprite is being drawn onto the screen, and it isn't moving up as it should when shoot() is called, although the sound still plays and no error occurs so shoot() IS being called :/

sprite.cs

protected Texture2D texture;
        protected Vector2 centre;
        protected Vector2 screenPos;
        protected Rectangle sourceRect;
        protected Vector2 velocity;

        public Sprite(Texture2D tex, Vector2 centre, Vector2 pos, Rectangle sourceRect, Vector2 vel)
        {
            texture = tex;
            this.centre = centre;
            this.screenPos = pos;
            this.sourceRect = sourceRect;
            this.velocity = vel;
        }
public virtual void Update(GameTime gameTime, Rectangle viewportRect)
        {
screenPos += velocity;
            // Check for collision with right edge, if so, bounce 
            if (screenPos.X + sourceRect.Width / 2 > viewportRect.Right)
            {
                velocity.X *= -0;
                screenPos.X = viewportRect.Right - sourceRect.Width / 2;
            }

            ...... etc
}

public virtual void Draw(GameTime gameTime, SpriteBatch sb, Color c)
        {
            sb.Draw(texture, screenPos, sourceRect, c,
                0.0f, centre, 1.0f, SpriteEffects.None, 0);
        }



player.cs

        public Player(Texture2D tex, Vector2 centre, Vector2 pos, Rectangle sourceRect, Vector2 vel) :
            base(tex, centre, pos, sourceRect, vel)
        {
        }


        public override void Update(GameTime gameTime, Rectangle viewportRect)
        {
            ProcessInput();

            base.Update(gameTime, viewportRect);
            velocity *= 0.95f;
        }


        protected void ProcessInput()
        {
GamePadState currentState = GamePad.GetState(PlayerIndex.One);

            velocity.X += currentState.ThumbSticks.Left.X;
            velocity.Y -= currentState.ThumbSticks.Left.Y;
}
public override void Draw(GameTime gameTime, SpriteBatch sb, Color c)
        {
            sb.Draw(texture, screenPos, sourceRect, c,
                            0.0f, centre, 0.6f, SpriteEffects.None, 0);


        }
    }
}




Bullet.cs

public Texture2D texture;

        public Vector2 position;
        public Vector2 velocity;
        public Vector2 origin;

        public bool isVisible;

        public Bullet (Texture2D newTexture)
        {
            texture = newTexture;
            isVisible = false;
        }

        public void Draw(SpriteBatch spriteBatch)
        {
            spriteBatch.Draw(texture, position, null, Color.White, 0f, origin, 1f, SpriteEffects.None, 0);
        }



Game1.cs

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 SpaceInvaders
{
    /// <summary>
    /// This is the main type for your game
    /// </summary>
    public class Game1 : Microsoft.Xna.Framework.Game
    {
        GraphicsDeviceManager graphics;
        SpriteBatch spriteBatch;
        Rectangle viewportRect;
        Boolean lastPlay = false;

        public static SoundEffect shootLaser, song;
        public static SoundEffectInstance shootLaserInstance, songInstance;

        private Sprite spaceship, enemy1;

        public static int screenHeight;
        public static int screenWidth;

        bool isDecending;
        bool isRight;
        const int noOfXInvaders = 7;
        const int noOfYInvaders = 3;
        Rectangle[,] recInvader = new Rectangle[noOfXInvaders, noOfYInvaders];
        Texture2D texInvader;
        Vector2 spritePosition;
        float rotation;

        List<Bullet> bullets = new List<Bullet>();



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

        /// <summary>
        /// Allows the game to perform any initialization it needs to before starting to run.
        /// This is where it can query for any required services and load any non-graphic
        /// related content.  Calling base.Initialize will enumerate through any components
        /// and initialize them as well.
        /// </summary>
        protected override void Initialize()
        {
            for (int x = 0; x < noOfXInvaders; x++)
            {
                for (int y = 0; y < noOfYInvaders; y++)
                {
                    recInvader[x, y] = new Rectangle(x * 45, y * 35, 30, 26);
                }
            }

            isRight = true;

            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()
        {
            spriteBatch = new SpriteBatch(GraphicsDevice);

            viewportRect = new Rectangle(0, 0,
                GraphicsDevice.Viewport.Width,
                GraphicsDevice.Viewport.Height);

            texInvader = this.Content.Load<Texture2D>("Textures\\enemy1");
            Texture2D spaceshipTex = Content.Load<Texture2D>("Textures\\spaceship");
            Texture2D enemy1Tex = Content.Load<Texture2D>("Textures\\enemy1");

            shootLaser = Content.Load<SoundEffect>("sounds\\laser");
            shootLaserInstance = shootLaser.CreateInstance();

            song = Content.Load<SoundEffect>("sounds\\song");
            songInstance = song.CreateInstance();

            songInstance.IsLooped = true;

            spaceship = new Player(spaceshipTex,
            new Vector2(spaceshipTex.Width / 2, spaceshipTex.Height / 2),
            new Vector2(250, 380),
            new Rectangle(0, 0, spaceshipTex.Width, spaceshipTex.Height),
            new Vector2(8, 3)
            );

            enemy1 = new Player(enemy1Tex,
            new Vector2(enemy1Tex.Width / 2, enemy1Tex.Height / 2),
            new Vector2(50, 50),
            new Rectangle(0, 0, enemy1Tex.Width, enemy1Tex.Height),
            new Vector2(8, 3)
            );






        }

        /// <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)
        {
            // Allows the game to exit

            songInstance.Play();
 
            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
                this.Exit();

            GamePadState gamepad = GamePad.GetState(PlayerIndex.One);

                //GamePad.SetVibration(PlayerIndex.One,
                //    gamepad.Triggers.Left,
                //    gamepad.Triggers.Right);

            if ((gamepad.Triggers.Right > 0) && (lastPlay == false))
            {
                if (shootLaserInstance.State == SoundState.Stopped)
                {
                    shootLaserInstance.Play();
                    Shoot();
                    lastPlay = true;
                }
                else if (shootLaserInstance.State == SoundState.Paused)
                {
                    shootLaserInstance.Resume();
                }
            }

            else if ((gamepad.Triggers.Right == 0) && (lastPlay == true))
            {
                lastPlay = false;
            }

            if (!isDecending)
            {
                for (int x = 0; x < noOfXInvaders; x++)
                {
                    for (int y = 0; y < noOfYInvaders; y++)
                    {
                        if (isRight) recInvader[x, y].X += 2;
                        else recInvader[x, y].X -= 2;
                    }
                }

                for (int x = 0; x < noOfXInvaders; x++)
                {
                    for (int y = 0; y < noOfYInvaders; y++)
                    {
                        bool hitLeft = recInvader[x, y].X == 0;
                        bool hitRight = recInvader[x, y].Right == screenWidth;
                        if ((hitLeft) || (hitRight))
                        {
                            isRight = !isRight;
                            isDecending = true;
                        }
                    }
                }
            }

            else
            {
                isDecending = false;

                for (int x = 0; x < noOfXInvaders; x++)
                {
                    for (int y = 0; y < noOfYInvaders; y++)
                    {
                        recInvader[x, y].Y += recInvader[x, y].Height;
                    }
                }

            }







            UpdateBullets();
            spaceship.Update(gameTime, viewportRect);

  

            base.Update(gameTime);
        }


        public void UpdateBullets()
        {
            foreach (Bullet bullet in bullets)
            {
                bullet.position += bullet.velocity;
                if (Vector2.Distance(bullet.position,spritePosition) > 500)
                {
                    bullet.isVisible = false;
                }

                for (int i = 0; i < bullets.Count; i++)
                {
                    if (!bullets[i].isVisible)
                    {
                        bullets.RemoveAt(i);
                        i--;
                    }
                }
            }
        }

        public void Shoot()
        {
            Bullet newBullet = new Bullet(Content.Load<Texture2D>("Textures\\bullet"));
            newBullet = new Vector2((float)Math.Cos(rotation), (float)Math.Sin(rotation)) * 5f + spriteVelocity;
            newBullet.position = spritePosition + newBullet.velocity * 5;
            newBullet.isVisible = true;

            if (bullets.Count() < 20)
            {
                bullets.Add(newBullet);
            }
        }


        /// <summary>
        /// This is called when the game should draw itself.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Draw(GameTime gameTime)
        {
            GraphicsDevice.Clear(Color.Black);
            spriteBatch.Begin();
            enemy1.Draw(gameTime, spriteBatch, Color.White);
            spaceship.Draw(gameTime, spriteBatch, Color.White);

            for (int x = 0; x < noOfXInvaders; x++)
            {
                for (int y = 0; y < noOfYInvaders; y++)
                {
                    spriteBatch.Draw(texInvader, recInvader[x, y], Color.Red);
                }
            }

            foreach (Bullet bullet in bullets)
            {
                bullet.Draw(spriteBatch);
            }
            



            spriteBatch.End();

            base.Draw(gameTime);
        }
    }
}



Thank you so much for any help as it's driving me crazy! :)

Is This A Good Question/Topic? 0
  • +

Replies To: Getting spaceship to fire (Space Invaders 'clone')

#2 foohoo  Icon User is offline

  • New D.I.C Head

Reputation: 2
  • View blog
  • Posts: 41
  • Joined: 10-August 07

Re: Getting spaceship to fire (Space Invaders 'clone')

Posted 04 October 2012 - 01:37 AM

Hi!

I am fairly new to this but I was taking a look before I start work :). The bit that's confusing me is in your shoot() method:

Bullet newBullet = new Bullet(Content.Load<Texture2D>("Textures\\bullet"));  

newBullet = new Vector2((float)Math.Cos(rotation), (float)Math.Sin(rotation)) * 5f + spriteVelocity;  



The first line looks fine for creating a new instance of Bullet, but I'm not too sure about the second line. Should this be setting newBullet.origin? At the moment it looks like it is just setting newBullet to a Vector2.

I have been able to run it myself but that was the first thing that confused me (but it doesn't take a lot to do that).

Cheers!
Was This Post Helpful? 0
  • +
  • -

#3 mxa92  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 11
  • Joined: 22-November 11

Re: Getting spaceship to fire (Space Invaders 'clone')

Posted 04 October 2012 - 11:34 AM

Sorry, that was supposed to be commented out as it was from another projectile tutorial I was trying to follow.

I've changed the Shoot() method so that the bullet should appear at position 100,100 with origin 100,100 but no Sprite is drawn on the screen at all still :S

shoot.cs

public void Shoot()
        {
            Bullet newBullet = new Bullet(Content.Load<Texture2D>("Textures\\bullet"));

            newBullet.origin = new Vector2(100,100);
            newBullet.position = new Vector2(100,100);
            newBullet.isVisible = true;

            if (bullets.Count() < 20)
            {
                bullets.Add(newBullet);
            }

            spriteBatch.Begin();
            foreach (Bullet bullet in bullets)
            {
                bullet.Draw(spriteBatch);
            }
            spriteBatch.End();

           

        }

Was This Post Helpful? 0
  • +
  • -

#4 mxa92  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 11
  • Joined: 22-November 11

Re: Getting spaceship to fire (Space Invaders 'clone')

Posted 06 October 2012 - 02:46 PM

I know it's been a while and nobody has commented back but just incase anyone was looking into this for me - I've managed to finish it myself :)

Thank you
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1