In a game I am working on, I am having an issue with making the player's ship shoot multiple bullets. The bullets have individual X and Y coordinates and velocity for X and Y. When I press "SPACE" to shoot the bullet, only one comes out, and when I release the space bar, the bullet disappears. I want to make multiple bullets without having to make an array since the amount of shots would be limited to the array size.

How do I make multiple instances of an object with data without using an array?

  • 2
    \$\begingroup\$ You cannot hold a variable amount of instances of an object without an array. If you are worried about bounds, use a standard vector: en.cppreference.com/w/cpp/container/vector \$\endgroup\$ – Luke San Antonio Bialecki Apr 6 '13 at 2:53
  • 1
    \$\begingroup\$ More correct to say that you need a container, not an array. Could use a list, set, map, deque, or one of the other possible containers. Arrays are best for most purposes, even if they don't resize: there is a gameplay-implicit limit to the number of billets, so it makes some sense to just use an appropriately sized array. \$\endgroup\$ – Sean Middleditch Apr 6 '13 at 3:27

As Sean said, you should use a STL container if you do not want to use a fixed sized array. The problem is that you will be tempted to insert or delete random elements relatively often. Instead of using a fixed sized array, I recommend using a std::vector, which basically is an array (at least in memory) with some additional features. In contrast to std::list, the data lies continuously in memory and thus calculations as physics and collision detection can be done effectively. Furthermore, it automatically does the resizing for your, so you will not have problem if you cannot determine a 'gameplay-implicit limit' for the number of bullets.

Furthermore, as I said, you will be tempted to delete random elements in the vector. Instead, do this: For each bullet, set a boolean alive flag. This will be true if the element of the vector represents a bullet which currently is flying through space and will be false if the element of the vector represents a 'free' slot. Use this 'free' slot when creating new bullets.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.