Creating and destroying new objects on the screen

Started by
1 comment, last by uncle_rico 18 years, 4 months ago
Hello there. I'm currently writing a simple 2D collision detection demo with "ball" sprites. It starts off with just one ball, that appears in the middle of the screen and shoots off in a random direction. By hitting the space bar, you can create a new ball, which also appears in the middle of the screen and shoots off in a random direction. You can keep on creating new balls as many times as you can hit the space bar. So, the problem I've run into is this. I want these "balls" to be global. I created a Ball class which stores all the info necessary for the ball. So, I supposed I could just declare the following globally: Ball ball[8]; And then just give the Ball class an on/off property that I can use to hide the balls that shouldn't be there. The problems I can't seem to get around are: a) I have to create a maximum number of balls (8 in this example). What if I want the user to be able to create as many as they want? b) It seems like a waste of space to declare balls that aren't yet in use. The higher the maximum, the more the waste. Item (b) seems especially problematic when I consider what it means for larger games -- does one have to declare every object that could possibly appear in the game right away, knowing that most everything declared will be "hidden?" Is there any way around this?
Advertisement
Look into std::vector<Ball> or std::list<Ball>. You can push_back as many as memory will allow really...
Excellent. And I don't know why I didn't think of linked lists. Oh well, a vector would be even better. Thanks!

This topic is closed to new replies.

Advertisement