Ok so I'm starting a project with a friend of mine, that's a 2D game in Java actually, but the question should be universal. It's not really a syntax question, just a logic question.
Ok so the game is a top down tower defense game (Think of Bloons TD). Right now I have classes for each of the towers all inheriting from a parent tower class. How do I keep track of all the towers built during runtime?
Two ways I can think of (not sure how they'll apply to Java).
1) A collection class. Make a collection class that stores an array of objects. It means the memory allocation is static and it may not be the most efficient but you'll have to weigh up those overheads. You could have the objects report whether they're active or not and whenever you want to reuse an object, just check the collection for an inactive object. Probably not explained to well, that one, but let me know if you get me.
2) May be simpler and better for dynamic memory and you'll have to test to see if it works because I don't have to means to do so right now, but how about a static counter in the base class that gets incremented in the constructors and decremented in the destructors?
I was thinking about just storing them in a container, didn't think about having a class just for the container though.
How would I go about handling shooting with each of these towers? How I had in mind was something like this:
1) Loop through the container and have each tower check to see if it in range of something to shoot
2) If a tower is in range, pick a target and fire
3) If tower already has target, don't pick a new one unless current target has moved out of range, or died.
This sounds rather inefficient to me, and I feel like if the player has a lot of towers, they're going to shoot in a "wave" type manner. As in first built will shoot, then second, and so on, and this may become noticeable if a lot is on the screen.
Depends on your frame rate. I don't think it'll look like a wave. If your game runs at 60FPS and you loop through every tower at each frame I doubt you'll see any fixed pattern.
The collection class is essentially a container. It's methods will simply loop through the individual towers and call their methods, be it shooting or checking targets or whatever. The. It means you just need one instance of the collection in your main coding and one call to each function. No loops.
Best thing to do is to just have a play, see how it goes.
A target isn't going to enter the range of every tower at the exact same time so you don't have to worry about your towers firing at the exact same time. It should be a wave.
The parent class needs a static container to keep track of the child classes. How you would do this in java I do not know.