简体   繁体   中英

Unlimited number of bullets

I try to make shooter game on C# with SFML.NET, but I can`t imagine how to make an ability to shoot more than 1 bullet, because now I have just one null-object of bullet-class, and when player presses Space key this object gets link to the new bullet.

So, I have the Bullet-class, null-object

public static Bullet bullet = null;

and condition

if (Keyboard.IsKeyPressed(Keyboard.Key.Space)) 
{
   if(bullet == null) 
    bullet = new Bullet(t, p.rect.Left, p.rect.Top, p.reverse);
}

When bullet reaches the wall or enemy bullet object gets equated to null. The problem is to make ability to shoot more bullets before this bullet reaches the wall or enemy (and disappear). I think this is not a good solution to make null-objects for every possible pullet, because then we have limited amount of possible bullets.

I would not suggest creating a list of bullets, but rather an array of bullets.

When the key is pressed you could add another bullet to the array and run update logic on all bullets in the array.

This will also allow you to loop back to the beginning to re-use memory instead of infinitely growing a list.

So for example in your keyPressedEvent:

If space on keyboard is pressed
    Increment bulletCounter
    if(bulletCounter > length of bullets array)
        set bulletCounter = 0;
    Set bullets[bulletCounter] = new Bullet(parameters)

You should look into the basics of game programming. For this situation you would use an array to contain N number of bullets.

Bullet only equals null once here also static need not be used here...remove the if(bullet == null) and replace public static Bullet bullet = null; with List bullets; Something like this should work:

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

KeyPressed event

    if(Keyboard.IsKeyPressed(Keyboard.Key.Space))
    {
        bullets.Add(new Bullet(t, p.rect.Left, p.rect.Top, p.reverse));
    }

Instead of setting the bullet to null when it hits the wall, get rid of/Dispose of it, maybe bullets.Remove(). No sense in keeping it right? Hope this gets you where you need to go.

Edit: It might actually be smart to limit the number of bullets allowed to be created by creating an array instead of a list as another person mentioned. What if the space bar key got stuck?

Bullet[] bullets = new Bullet[1000];

Maybe something like that...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM