14 Replies - 617 Views - Last Post: 06 February 2013 - 06:48 AM Rate Topic: -----

#1 bboyzeez  Icon User is offline

  • D.I.C Head

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

trying to understand List<>

Posted 05 February 2013 - 04:21 AM

hi all , i know i have posted in XNA but i feel this is just general C# so i am posting a different question here

i am trying to get my spaceship to shoot bullets,

i have created a new list which is from the bullets class i made.
 List<Bullets> bullets = new List<Bullets>();


here is my bullets 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 a game component that implements IUpdateable.
    /// </summary>
    public class Bullets 
    {
        protected SpriteBatch sbBatch;

        public Texture2D bulletTexture;
        public Vector2 bulletPosition;
        public int YSpeed = 10;
        public Vector2 bulletOrigin;
        public Vector2 PlayerPosition;
        public bool isVisible;
        public PlayerIndex playerID;
        Vector2 player1position;

        protected List<Bullets> bullet;

        public Bullets(Game game, ref Texture2D theTexture, PlayerIndex playerID)            
        {
            bulletTexture = theTexture;
           
            isVisible = false;

            
        }

        public void Draw(SpriteBatch spriteBatch)
        {
            
            spriteBatch.Draw(bulletTexture,bulletPosition , null, Color.White, 0f, bulletOrigin, 1f, SpriteEffects.None, 0);
            
        }
    }
}



and in my "action scene" i have passed the texture through a component from the main game1 class, and then i have a update bullets and a shoot methods in the action scene.

public void UpdateBullets()

            {
                foreach (Bullets bullet in bullets)
                {
                    newbulletposition.Y += bullet.YSpeed;
                    if (Vector2.Distance(bullet.bulletPosition, player1.playerPosition) > 500)
                        bullet.isVisible = false;
                }

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

            public void Shoot()
            {
                Bullets newBullet = new Bullets(Game, ref bulletTexture, PlayerIndex.One);
                
                newBullet.bulletPosition = Vector2.Zero ;
                newBullet.isVisible = true;


            
            }



and then in the update of action scene i am handling the input so when the user presses the "B" button on controller it plays an explosion sound(using this sound just for testing will change once i get the bullets shooting sorted) and then triggers the shoot method

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

                if ( oldGamePadState.Buttons.B == ButtonState.Pressed && gamepadstate.Buttons.B == ButtonState.Released)
                    audio.Explosion.Play();
                    Shoot();

                oldGamePadState = gamepadstate;
                UpdateBullets();




my problem is when i press B the explosion plays but the bullets dont appear or move or anything.

also im unsure how i made a bullets list and then when i shoot i create a new "newbullet" i dont understand how that newbullet adds to the bullet list ?

Is This A Good Question/Topic? 0
  • +

Replies To: trying to understand List<>

#2 MrShoes  Icon User is offline

  • D.I.C Regular
  • member icon

Reputation: 313
  • View blog
  • Posts: 490
  • Joined: 13-June 12

Re: trying to understand List<>

Posted 05 February 2013 - 05:05 AM

You will need a reference to the List<Bullet> when you create it in the Shoot() method. Then use bulletList.Add(newBullet);

At the moment, you have a List<Bullet> called "bullet" that doesn't get added to. Your Shoot() method creates a new Bullet, sets a couple of its properties, then does nothing with it. That means that after the method, a reference to it is not held, so the Garbage Collector will clear it up.
Was This Post Helpful? 1
  • +
  • -

#3 bboyzeez  Icon User is offline

  • D.I.C Head

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

Re: trying to understand List<>

Posted 05 February 2013 - 05:14 AM

ahh ok i understand , i dont understand how this tutorial on youtube got his working when his didnt add to the list :s lol i will try this now and have a look thanks

the other thing im noticing is that when the list adds a new bullet and goes into the bullet class, it never goes into draw because obviusly i havent got the method called. so if i call the method to draw it in within the shoot method, where would i do the update of bullet position and collision, in the actionscne class or in the actual bullet class?
Was This Post Helpful? 0
  • +
  • -

#4 MrShoes  Icon User is offline

  • D.I.C Regular
  • member icon

Reputation: 313
  • View blog
  • Posts: 490
  • Joined: 13-June 12

Re: trying to understand List<>

Posted 05 February 2013 - 05:23 AM

Encapsulate everything within its own class. What I mean is, the Bullet class handles itself, the Player class too, any other classes handle their own behaviour, usually calling methods from an Update method. Drawing should be handled internally too. You should simply have collections of objects, then in the Game1.cs Update method, you call the update methods for each object in the collection. Same with Draw methods.
Was This Post Helpful? 1
  • +
  • -

#5 bboyzeez  Icon User is offline

  • D.I.C Head

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

Re: trying to understand List<>

Posted 05 February 2013 - 06:11 AM

ahhh i am really getting confused now lol

so all the other classes are dereived from something , but the bullet class is separate (i dont understand why this would be?) so because it is separate it cannot override draw so when it has its own Draw method and i call it from the Shoot method in actionscene , i get the error "Begin must be called successfully before a Draw can be called." error?

would it be best i include the code for action scene , main game , player and bullet? no need to include rest of coding for help screen and meteors etc?
Was This Post Helpful? 0
  • +
  • -

#6 bboyzeez  Icon User is offline

  • D.I.C Head

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

Re: trying to understand List<>

Posted 05 February 2013 - 06:21 AM

EDIT; i made the bullet class derive from DrawableGameComponent in order to override draw but im still getting the same error when it comes to draw the image as above
Was This Post Helpful? 0
  • +
  • -

#7 MrShoes  Icon User is offline

  • D.I.C Regular
  • member icon

Reputation: 313
  • View blog
  • Posts: 490
  • Joined: 13-June 12

Re: trying to understand List<>

Posted 05 February 2013 - 06:22 AM

You're following a video tutorial right? My current guess is that it's not very good... I tried a video tutorial when learning XNA, and I realised afterwards that it was terrible and taught things all wrong.

How I would do things for your scenario is to add an abstract class (or an interface, if you're ready) called GameObject, with an Update and Draw method. Then inherit from that class for Player, Bullet, etc. and store all the GameObjects in a collection in the Game1 class. That way, the Update() method will just call the Update() for each entry in the collection. It seperates the concerns, because the game doesn't really need to know what a bullet does to update, just needs to tell it to do it.
Was This Post Helpful? 0
  • +
  • -

#8 pharylon  Icon User is offline

  • D.I.C Head

Reputation: 40
  • View blog
  • Posts: 83
  • Joined: 01-September 12

Re: trying to understand List<>

Posted 05 February 2013 - 06:34 AM

Quote

so all the other classes are dereived from something , but the bullet class is separate (i dont understand why this would be?) so because it is separate it cannot override draw so when it has its own Draw method and i call it from the Shoot method in actionscene , i get the error "Begin must be called successfully before a Draw can be called." error?


No, what he means is you want all Classes to be totally unconcerned with each other. The bullet class shouldn't know ANYTHING about the gamepad. You should have a class who's job is to keep track of the game and serve as a layer between the user and sending out commands to all the other classes (this is part of the idea of encapsulation).

So the bullet class should have a Shoot() method to generate new bullets and maybe a UpdateLocation() method to move them along with each tick of the game clock, etc. But, you should have a controller class that instantiates that bullet class, calls the Shoot() method when a bullet is fired, calls the UpdateLocation() method each time the clock ticks, etc. When the user presses B, that should be something the controller is watching for, and then the controller can send the appropriate commands to the appropriate subclasses (if B is a bomb, for instance, it needs to send that information to a Bomb class instead of the Bullet class).

Encapsulation means each class has a very specific job, and is on a need-to-know basis. Bullets don't need to know what's going on with the gamepad, they only need to know how to be created, how much damage they do, how they move, etc. It's up to another class to get user input and then tell the bullets to be doing their things.

If I can throw this out there, you seem to be jumping into software development learning some "how" stuff but not the "why." If I can suggest a book for you, go pick up "Visual C# Step by Step". It's one of the two I'm using to get a good understanding of the C# language, and the one that's better for explaining the whys. Once you understand the whys, you're going to hit a lot fewer roadblocks like this.

This post has been edited by pharylon: 05 February 2013 - 06:36 AM

Was This Post Helpful? 1
  • +
  • -

#9 bboyzeez  Icon User is offline

  • D.I.C Head

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

Re: trying to understand List<>

Posted 05 February 2013 - 07:06 AM

yes , i following this book and i have go to the end and it seems i have just wrote line for line but the book did go into depth on most things, i am now going back using what i have done at the moment as a guide but writing it again making sure i understand it all.

MrShoes as for what you were saying , i think this tutorial did this without explaining much about it , in the game 1 class i created componets which added the elements needed for each scene so thats what i did i added my bullet texture to the same action scene so it was stored but yes i am making it again , i have picked better graphics and this way i am learning and understand each area more. so far i have a main game class and then a player class which at the moment draws the ship onto screen and im jst playing with the input and getting the ship to stay in screenbounds , then i will focus on the bullet class , then its just the meteors which i understood before so i should be fine once i get this done
Was This Post Helpful? 0
  • +
  • -

#10 pharylon  Icon User is offline

  • D.I.C Head

Reputation: 40
  • View blog
  • Posts: 83
  • Joined: 01-September 12

Re: trying to understand List<>

Posted 05 February 2013 - 07:11 AM

Quote

yes , i following this book and i have go to the end and it seems i have just wrote line for line but the book did go into depth on most things, i am now going back using what i have done at the moment as a guide but writing it again making sure i understand it all.


Yeah, that's the problem with it, but I felt like it gave me a solid understanding of theory. For concrete practice, I highly recommend "Head First C#" by O'Reilly Press. It gives you a lot of work to do where it doesn't give you the answers right away. These two books together are perfect matches IMO. By the end of "Head First C#" you're creating an Asteroids clone.
Was This Post Helpful? 1
  • +
  • -

#11 bboyzeez  Icon User is offline

  • D.I.C Head

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

Re: trying to understand List<>

Posted 05 February 2013 - 10:34 AM

can someone help me with this error ,

i am trying to get so when the shoot method is called inside Lacer class it gets the ship position, then create a new laser with this new position but the first argument game says it does not exsist in the context

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 Move__shoot
{   /// <summary>
    /// This is a game component that implements a laser
    /// 
    /// </summary>
    /// 

        
    public class Laser : DrawableGameComponent
    {
        protected Texture2D laserTexture;   // Sprite texture
        protected Vector2 laserPosition; // Sprite Position
        protected Rectangle laserRectangle;
        protected SpriteBatch laserBatch;

        //width and height of ship in texture
        protected const int LASERWIDTH = 70;
        protected const int LASERHEIGHT = 72;

        //screen area
        private Rectangle screenBounds;

        List<Laser> lasers = new List<Laser>();


        
        public Laser(Game game, ref Texture2D theTexture, Vector2 shipPos)
            : base(game)
        {
            laserTexture = theTexture;
            laserPosition = shipPos;

            laserBatch = (SpriteBatch)
                game.Services.GetService(typeof(SpriteBatch));

            laserRectangle = new Rectangle(0, 0, LASERWIDTH, LASERHEIGHT);




            screenBounds = new Rectangle(
               0, 0, game.window.ClientBounds.Width, game.window.ClientBounds.Height);


        }

        public override void Draw(GameTime gameTime)
        {

            laserBatch.Draw(laserTexture, laserPosition, Color.White);
            
            base.Draw(gameTime);
        }

        /// <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)
        {
            GamePadState gamepadstatus = GamePad.GetState(PlayerIndex.One);
            


            if (gamepadstatus.Buttons.B == ButtonState.Pressed)
            {
                UpdateLaser();

            }
            if (gamepadstatus.Buttons.A == ButtonState.Pressed)
            {
                Shoot();

            }
            UpdateLaser();
            base.Update(gameTime);
        }

        public void UpdateLaser()
        {

            laserPosition += new Vector2(0, -5);
        }


        public void Shoot()
        {
            Player newplayer = new Player(Game); (i am doing this line so i can find the current position of the ship in player class)
            
            Laser newlaser = new Laser(game, ref laserTexture, newplayer.GetShipPosition); <<<<<THIS LINE ERRORS
            

        }
    }
}


Was This Post Helpful? 0
  • +
  • -

#12 Skydiver  Icon User is offline

  • Code herder
  • member icon

Reputation: 3621
  • View blog
  • Posts: 11,280
  • Joined: 05-May 12

Re: trying to understand List<>

Posted 05 February 2013 - 10:58 AM

You need uppercase Game, not lowercase game.

http://msdn.microsof...onent.game.aspx
Was This Post Helpful? 0
  • +
  • -

#13 JimPickens  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 24
  • Joined: 05-February 13

Re: trying to understand List<>

Posted 05 February 2013 - 03:21 PM

I think you should look at this. http://www.dreaminco...lasses-objects/
Was This Post Helpful? 0
  • +
  • -

#14 robostealth  Icon User is offline

  • New D.I.C Head

Reputation: 2
  • View blog
  • Posts: 10
  • Joined: 06-February 13

Re: trying to understand List<>

Posted 06 February 2013 - 02:00 AM

View Postbboyzeez, on 05 February 2013 - 04:21 AM, said:

            public void Shoot()
            {
                Bullets newBullet = new Bullets(Game, ref bulletTexture, PlayerIndex.One);
                
                newBullet.bulletPosition = Vector2.Zero ;
                newBullet.isVisible = true;


            
            }


this is where your problem is, which was explained, but i'll put it in your code.
instead of creating a bullet called newBullet, you should be creating a generic bullet and adding it to your bullet list. also, you're going to need quite a bit more information in your constructor, like the position of your "ship" (the position your bullet will be created at), among other things. but for the main problem:

            public void Shoot()
            {
                bullets.Add(new Bullets(/*Your constructor*/)


            
            }



And then somewhere in your game update method:
foreach (Bullets b in bullets) //you should really consider a better naming convention, like using bulletList for the list, for clarification
{
   b.Update(/*update stuff*/)
}



...And finally, you'll need a similar thing in your game's Draw method:
foreach (Bullets b in bullets) 
{
   b.Update(/*draw stuff*/)
}



using lists along with the foreach loop pretty much handles all of this stuff with ease, and use can use the same structure for most objects that you might have quite a few of and don't require individual input, like AI enemies, for example.
Was This Post Helpful? 1
  • +
  • -

#15 bboyzeez  Icon User is offline

  • D.I.C Head

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

Re: trying to understand List<>

Posted 06 February 2013 - 06:48 AM

thank you , yes from this last night i somehow come onto a thread in here which linked to the users youtube channel and i sat last night went from tutorial 1 -> 22(still going) and i honestly learnt more from this guy even though his pretty quick than this book i started with lol

btw dont know if user still comes on here or will see this but OYYOU91 THANK YOU :)

i now have started from beginning completly what you mean now (original question how can i get ships position in bullet class) with the constructors etc it all makes more sense thanks :)
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1