Domanda

i am currently doing a C# XNA course and this is the way they have implemented bullets. they say that the class will automatically iterate through the list (bullList). currently this is not working for me. can anyone give me a clue as to what i am doing wrong or point me to an example of a working version of this? thanks in advance

    class Bullet
{
    public Vector2 position;
    public Vector2 velocity;
    public Texture2D texture;
    public float speed;
    public Rectangle rectangle;
    public Vector2 size = new Vector2(16, 16);
    public List<Bullet> bullList = new List<Bullet>();
    public enum Owner
    {
        PLAYER,
        ENEMY
    }

    public Bullet()
    {
        Update();
    }

    public void Update()
    {
        rectangle = new Rectangle((int)position.X, (int)position.Y, (int)size.X, (int)size.Y);
        position += (velocity * speed);

    }

    public void Draw(SpriteBatch spriteBatch, Texture2D a_texture)
    {
        spriteBatch.Draw(a_texture, position, Color.White);
    }

    public void Shoot(Vector2 a_position, Vector2 a_velocity, float a_speed, Texture2D a_texture)
    {
        Bullet newBullet = new Bullet();
        newBullet.position = a_position;
        newBullet.velocity = a_velocity;
        newBullet.speed = a_speed;
        newBullet.texture = a_texture;
        newBullet.isAlive = true;
        bullList.Add(newBullet);
    }
}
È stato utile?

Soluzione

Both your draw and your update functions are working on the "main" instance of bullet. Instead, you need to run a foreach:

foreach (Bullet b in bullList)
{
   b.rectangle = new Rectangle((int)b.position.X, (int)b.position.Y, (int)b.size.X, (int)b.size.Y);
   b.position += (b.velocity * b.speed);
}

And a similar one for the draw loop.

That being said, I wouldn't do it this way. Bullets do not "have" bullets, a BulletManager might though. In other words, your main "bullet" has a list of all the "actual" bullets, and all the position variables aren't used, and the "actual" bullets have a list of sub-bullets they don't really need, but they use all the position variables. Sounds like a good case for two different objects to me :).

A few other things I noticed, the "Owner" enum is never used, neither is the "IsAlive" property. That might just get added later, but the lack of "IsAlive" could cause a performance issue after enough "fires" in testing.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top