4 Replies - 2650 Views - Last Post: 05 February 2013 - 01:49 AM

#1 bboyzeez  Icon User is offline

  • D.I.C Head

Reputation: 4
  • View blog
  • Posts: 143
  • Joined: 16-December 12

improving my simple 2d game

Posted 04 February 2013 - 08:35 AM

hi all , i have basically followed a book that has helped me create my first 2d game called RockRain it basically is a ship that has to dodge the oncoming meteors , at the end of the chapter it allowed me to create a start screen and 2 player mode with a health pick up item that also falls down same as a meteor

i have played it a few times now with other members of family to test for bugs but we all agree , a ship is useless without weapons lol , am i right in thinking i create a new list that creates a sprite of "laser or bullet" which travels the player position up to top of screen and then when it leaves the screen it just gets disposed?

as for collision i guess its the same as the meteor hitting the player except when the laser hits the meteor that meteor will just dissapear?(maybe include a "blast sprite" once i got the initial shooting sorted.

thanks

Is This A Good Question/Topic? 0
  • +

Replies To: improving my simple 2d game

#2 Hezekiah  Icon User is offline

  • D.I.C Addict
  • member icon

Reputation: 207
  • View blog
  • Posts: 550
  • Joined: 12-July 09

Re: improving my simple 2d game

Posted 04 February 2013 - 09:39 AM

That sounds like it could work. Why don't you try to implement it and then come back if you have a problem you can't solve?
Was This Post Helpful? 2
  • +
  • -

#3 bboyzeez  Icon User is offline

  • D.I.C Head

Reputation: 4
  • View blog
  • Posts: 143
  • Joined: 16-December 12

Re: improving my simple 2d game

Posted 04 February 2013 - 04:25 PM

ok im stuck at a little hurdle, i have a player class which derives from the XNA DrawableGameComponent which holds all info on the player(spaceship)

and then my main game1 class derives from XNA Game

i basically understand that i need to set up the bullets in the bullets class and then have the main game 1 class create a new list for bullets and then to draw them in and update them , my problem is in player class i have my player position and i cant find a way of getting that vector value across to the game1 class , i think i have managed to get it to the bullets class and tbh that was where i originally designed i would do the draw and update but im following a guide and they use game1 class to draw and update.

if code is needed to help and this is right section for it then let me know and ill upload it up , i am committing the next few hours to try get my ship killing meteors but at the moment looking highly unlikely

thanks
Was This Post Helpful? 0
  • +
  • -

#4 macosxnerd101  Icon User is offline

  • Self-Trained Economist
  • member icon




Reputation: 10468
  • View blog
  • Posts: 38,799
  • Joined: 27-December 08

Re: improving my simple 2d game

Posted 04 February 2013 - 05:57 PM

Moving to XNA.

Please post your code.
Was This Post Helpful? 0
  • +
  • -

#5 bboyzeez  Icon User is offline

  • D.I.C Head

Reputation: 4
  • View blog
  • Posts: 143
  • Joined: 16-December 12

Re: improving my simple 2d game

Posted 05 February 2013 - 01:49 AM

ok thanks for moving it to correct place :) ok here is the main game class

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 RockRainEnhanced.Core;

namespace RockRainEnhanced
{
    /// <summary>
    /// This is the main type for your game
    /// </summary>
    public class Game1 : Game
    {
        private readonly GraphicsDeviceManager graphics;
        private SpriteBatch spriteBatch;
        private AudioLibrary audio;

        //game scenes
        protected HelpScene helpscene;
        protected GameScene activeScene;
        protected StartScene startScene;
        protected ActionScene actionscene;
        //texture
        protected Texture2D helpBackgroundTexture, helpForegroundTexture;
        protected Texture2D actionElementsTexture, actionBackgroundTexture;
        protected Texture2D startBackgroundTexture, startElementsTexture, bulletTexture;
        //fonts
        private SpriteFont smallFont, largeFont, scoreFont;

        //bullets
        public List<Bullets> bullets;
        Vector2 bulletpos = new Vector2(300f, 300f);

        //handle input
        protected KeyboardState oldKeyboardState;
        protected GamePadState oldGamePadState;

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

            // Used for input handling
            oldKeyboardState = Keyboard.GetState();
            oldGamePadState = GamePad.GetState(PlayerIndex.One);

            graphics.PreferredBackBufferWidth = 1600;
            graphics.PreferredBackBufferHeight =900;

            graphics.PreferMultiSampling = true;
        }

        /// <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()
        {
            // TODO: Add your initialization logic here

            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);
            Services.AddService(typeof(SpriteBatch), spriteBatch);

            //load audio elements
            audio = new AudioLibrary();
            audio.LoadContent(Content);
            Services.AddService(typeof(AudioLibrary), audio);

            // create the Credits / Instruction scene
            helpBackgroundTexture = Content.Load<Texture2D>("helpbackground");
            helpForegroundTexture = Content.Load<Texture2D>("helpforeground");
            helpscene = new HelpScene(this, helpBackgroundTexture, helpForegroundTexture);
            Components.Add(helpscene);

            
            
            // create the start scene
            smallFont = Content.Load<SpriteFont>("menuSmall");
            largeFont = Content.Load<SpriteFont>("menuLarge");
            startBackgroundTexture = Content.Load<Texture2D>("startbackground");
            startElementsTexture = Content.Load<Texture2D>("startSceneElements");
            startScene = new StartScene(this, smallFont, largeFont, startBackgroundTexture, startElementsTexture);
            Components.Add(startScene);

            

            // create the action scene
            actionElementsTexture = Content.Load<Texture2D>("rockrainenhanced");
            actionBackgroundTexture = Content.Load<Texture2D>("SpaceBackground");
            scoreFont = Content.Load<SpriteFont>("score");
            actionscene = new ActionScene(this, actionElementsTexture, actionBackgroundTexture, scoreFont);
            Components.Add(actionscene);

            startScene.Show();
            activeScene = startScene;

            
            bulletTexture = Content.Load<Texture2D>("Bullets");
            
            
        }

        /// <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
            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
                this.Exit();

           //handle game inputs
            HandleScenesInput();

            base.Update(gameTime);
        }

        //handle scenesinput
        private void HandleScenesInput()
        {
            //handle start screen input
            if (activeScene == startScene)
            {
                HandleStartSceneInput();
            }
            //handle help scene input
            else if (activeScene == helpscene)
            {
                if (CheckEnterA())
                {
                    ShowScene(startScene);
                }
            }

            //handle action scene input

            else if (activeScene == actionscene)
            {
                HandleActionInput();
            }
            }

        




        //check if enter key o A button was pressed
        private bool CheckEnterA()
        {
            //get keyboard and gamepad state
            GamePadState gamepadstate = GamePad.GetState(PlayerIndex.One);
            KeyboardState keyboardState = Keyboard.GetState();

            bool result = (oldKeyboardState.IsKeyDown(Keys.Enter) && (keyboardState.IsKeyUp(Keys.Enter)));

            result |= (oldGamePadState.Buttons.A == ButtonState.Pressed) && gamepadstate.Buttons.A == ButtonState.Released;

            oldGamePadState = gamepadstate;
            oldKeyboardState = keyboardState;

            return result;
                
        }

        //handle button and keyboard in start scene
        private void HandleStartSceneInput()
        {
            if (CheckEnterA())
            {
                audio.MenuSelect.Play();
                switch (startScene.SelectedMenuIndex)
                {
                    case 0:
                        actionscene.TwoPlayers = false;
                        ShowScene(actionscene);
                        break;
                    case 1:
                        actionscene.TwoPlayers = true;
                        ShowScene(actionscene);
                        break;
                    case 2:
                        ShowScene(helpscene);
                        break;
                    case 3:
                        Exit();
                        break;
                }
        }
        }

        // check if key or button was pressed
        private void HandleActionInput()
        {
            //get the keyboard and gamepad state
            GamePadState gamepadState = GamePad.GetState(PlayerIndex.One);
            KeyboardState keyboardState = Keyboard.GetState();

            bool backKey = (oldKeyboardState.IsKeyDown(Keys.Escape) &&
                (keyboardState.IsKeyUp(Keys.Escape)));

            backKey |= (oldGamePadState.Buttons.Back == ButtonState.Pressed) &&
                (gamepadState.Buttons.Back == ButtonState.Released);

            bool enterKey = (oldKeyboardState.IsKeyDown(Keys.Enter) &&
                (keyboardState.IsKeyUp(Keys.Enter)));

            enterKey |= (oldGamePadState.Buttons.A == ButtonState.Pressed) &&
                (gamepadState.Buttons.A == ButtonState.Released);

            oldKeyboardState = keyboardState;
            oldGamePadState = gamepadState;

            if (enterKey)
            {
                if(actionscene.GameOver)
                {
                    ShowScene(startScene);
                }
                else{
                    audio.MenuBack.Play();
                    actionscene.Paused = !actionscene.Paused;
                }
            }

            if (backKey)
            {
                ShowScene(startScene);
            }
        }
         
        //open a new scene
        protected void ShowScene(GameScene scene)
        {
            activeScene.Hide();
            activeScene = scene;
            scene.Show();
        }

        
    


        /// <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)
        {
            spriteBatch.Begin();
            
            base.Draw(gameTime);
            //spriteBatch.Draw(bulletTexture, bulletpos, Color.White);
            spriteBatch.End();
        }
    }
}



here is the player(spaceship) class
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 RockRainEnhanced
{
    /// <summary>
    /// This is a game component that implements the players ship
    /// </summary>
    public class Player :DrawableGameComponent
    {

        protected Texture2D texture;
        protected Rectangle spriteRectangle;
        protected Vector2 position;
        protected TimeSpan elapsedTime = TimeSpan.Zero;
        protected PlayerIndex playerIndex;
        protected SpriteBatch sBatch;

        public Vector2 playerPosition;

        //screen area
        protected Rectangle screenBounds;

        //game stuff
        protected int score;
        protected int power;
        private const int INITIALPOWER = 100;

        

        
        
        public Player(Game game, ref Texture2D theTexture, PlayerIndex playerID,Rectangle rectangle)
            : base(game)
        {
            texture = theTexture;
            position = new Vector2();
            playerIndex = playerID;
            playerPosition = position;
            sBatch = (SpriteBatch)
                Game.Services.GetService(typeof(SpriteBatch));



            //create the source rectangle
            //this represents where the sprite picture is in surface
            spriteRectangle = rectangle;

            screenBounds = new Rectangle((int)(Game.window.ClientBounds.Width*0.03f),
                        (int) (Game.window.ClientBounds.Height * 0.03f), (int) Game.window.ClientBounds.Width - 
                            (int) (Game.window.ClientBounds.Width*0.03f),
                            Game.window.ClientBounds.Height - 
                                (int)(Game.window.ClientBounds.Height*0.03f));

            
        }


        //put the ship back in start position
        public void Reset()
        {
            if (playerIndex == PlayerIndex.One)
            {
                position.X = screenBounds.Width / 3;
            }
            else
            {
                position.X = (int)(screenBounds.Width / 1.5);
            }

            position.Y = screenBounds.Height - spriteRectangle.Height;
            score = 0;
            power = INITIALPOWER;


        }

        // try to get player position
        public Vector2 GetPlayerPosition
        {
            get { return position; }
            
        }

        //total points of the player
        public int Score
        {
            get { return score; }
            set
            {
                if (value < 0)
                {
                    score = 0;
                }
                else
                {
                    score = value;
                }
            }
        }

        //remaining power
        public int Power
        {
            get { return power; }
            set { power = value; }
        }
        /// <summary>
        /// Allows the game component to perform any initialization it needs to before starting
        /// to run.  This is where it can query for any required services and load content.
        /// </summary>
        public override void Initialize()
        {
            // TODO: Add your initialization code here

            base.Initialize();
        }

        /// <summary>
        /// update the ship position, points and power
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        public override void Update(GameTime gameTime)
        {
            //xbox controller
            GamePadState gamepadstatus = GamePad.GetState(playerIndex);
            position.Y += (int)((gamepadstatus.ThumbSticks.Left.Y * 3) * -2);
            position.X += (int)((gamepadstatus.ThumbSticks.Left.X * 2) * 2);


            //keyboard
            if (playerIndex == PlayerIndex.One)
            {
                HandlePlayer1KeyBoard();
            }
            else
            {
                HandlePlayer2KeyBoard();
            }
            

            //keep the player inside the screen
            KeepInBound();

            //Update Score
            elapsedTime += gameTime.ElapsedGameTime;

            if (elapsedTime > TimeSpan.FromSeconds(1))
            {
                elapsedTime -= TimeSpan.FromSeconds(1);
                score++;
                power--;
            }
            
            
            
            base.Update(gameTime);
        }

        //keep ship in screen
        private void KeepInBound()
        {
            if (position.X < screenBounds.Left)
            {
                position.X = screenBounds.Left;
            }
            if (position.X> screenBounds.Width-spriteRectangle.Width)
            {
                position.X = screenBounds.Width-spriteRectangle.Width;
            }
            if(position.Y < screenBounds.Top)
            {
                position.Y = screenBounds.Top;
            }
            if (position.Y > screenBounds.Height - spriteRectangle.Height)
            {
                position.Y = screenBounds.Height - spriteRectangle.Height;
            }
        }

        //handle keys for player 1 ASDW
        private void HandlePlayer1KeyBoard()
        {
            KeyboardState keyboard = Keyboard.GetState();
            if (keyboard.IsKeyDown(Keys.W))
            {
                position.Y -= 3;
            }
            if (keyboard.IsKeyDown(Keys.S))
            {
                position.Y += 3;
            }
            if (keyboard.IsKeyDown(Keys.A))
            {
                position.X -= 3;
            }
            if (keyboard.IsKeyDown(Keys.D))
            {
                position.X += 3;
            }
        }

        //handle keys for player 2 arrows
        private void HandlePlayer2KeyBoard()
        {
            KeyboardState keyboard = Keyboard.GetState();
            if (keyboard.IsKeyDown(Keys.Up))
            {
                position.Y -= 3;
            }
            if (keyboard.IsKeyDown(Keys.Down))
            {
                position.Y += 3;
            }
            if (keyboard.IsKeyDown(Keys.Left))
            {
                position.X -= 3;
            }
            if (keyboard.IsKeyDown(Keys.Right))
            {
                position.X += 3;
            }
        }

        //draw ship sprite
        public override void Draw(GameTime gameTime)
        {

            
            //get current sprite batch
            sBatch = (SpriteBatch)
                Game.Services.GetService(typeof(SpriteBatch));

            //draw the ship
            sBatch.Draw(texture, position, spriteRectangle, Color.White);



            
            
            base.Draw(gameTime);
        }

        //get bound rectangle of ship position
        public Rectangle GetBounds()
        {
            return new Rectangle((int)position.X, (int)position.Y,
                spriteRectangle.Width, spriteRectangle.Height);
            
        }


    }
}




and finally my bullet class which i just made
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 RockRainEnhanced.Core;


namespace RockRainEnhanced
{
    /// <summary>
    /// This is a game component that implements IUpdateable.
    /// </summary>
    public class Bullets : Player
    {
        //SpriteBatch spriteBatch;

        public Texture2D bulletTexture;
        public Vector2 bulletPosition;
        public Vector2 bulletVelocity;
        public Vector2 bulletOrigin;
        public Vector2 PlayerPosition;
        public bool isVisible;

        protected List<Bullets> bullet;

        public Bullets(Game game, ref Texture2D theTexture, PlayerIndex playerID, Rectangle rectangle)
            :base(game,ref theTexture,playerID,rectangle)
        {
            bulletTexture = theTexture;
            isVisible = false;
        }

        /// <summary>
        /// Allows the game component to perform any initialization it needs to before starting
        /// to run.  This is where it can query for any required services and load content.
        /// </summary>
        public override void Initialize()
        {
            // TODO: Add your initialization code here
            
            base.Initialize();
        }

        /// <summary>
        /// Allows the game component to update itself.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        public override void Update(GameTime gameTime)
        {
            // TODO: Add your update code here
            Vector2 player1position =  GetPlayerPosition;
            PlayerPosition = player1position;
            base.Update(gameTime);
        }

        public override void Draw(GameTime gameTime)
        {
            
            //spriteBatch.Draw(bulletTexture, position, null, Color.White, 0f, bulletOrigin, 1f, SpriteEffects.None, 0);
            
            base.Draw(gameTime);
        }
    }
}





my problems are as follows

1. if i try to derive the bullet class from player that can get me the players position but then i not quite sure how to load the bullet image into the main game class to make it work in the bullet/player class

2. if i make the bullet class and then control it from the main game class where i understand how to load it up and draw it i then cant get to the players position value in order to make the bullets shoot from ship?

thanks
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1