Take the 2-minute tour ×
Game Development Stack Exchange is a question and answer site for professional and independent game developers. It's 100% free, no registration required.

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?

share|improve this question
2  
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 –  Luke San Antonio Apr 6 '13 at 2:53
1  
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. –  Sean Middleditch Apr 6 '13 at 3:27
add comment

1 Answer

up vote 1 down vote accepted

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.

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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