I've been building a game in C++ using SDL and I've run into a problem I'm not sure how to fix (or maybe it's just a limitation of SDL)
So I've got a "GameObject" class with a "draw" method that draws the object's sprite on the screen (obviously), and then have objects that extend if (like the player, enemies, weapons etc.); these all work fine. Then I have a Game object that handles the main game loop. This is the object where the trouble is coming from. Specifically this code:
while(running)
{
// Clear the previous frame
SDL_RenderClear(window->get_renderer()); // Oh yeah, I had a Window class too; this works though
// Draw all the objects in the "objects" vector
if (!objects.empty())
for (GameObject * o : objects)
o->draw(window->get_surface());
// Handle keyboard events etc.
}
This is the loop that handles keyboard events, draws the background on the screen, etc. But the code that handles drawing seems to be the problem here. In the for loop, "objects" is a vector of pointers to GameObject instances, and it works fine for objects created in main().So for the player, the one enemy ship I have, and pretty much anything I know is going to be there at compile time, this works great. Anything I can create before calling Game.start (where the code above is executed) will be drawn on the screen. The problem is with objects added to the vector during the game.
For example, this game is a 2D scroller with a space ship that shoots lasers. In the loop above, if the user presses Space it creates a laser object and adds it to the "objects" vector. Those objects are created and added to the vector (tested with a bunch of cout calls) but mysteriously never get drawn.
So my questions are:
1. Has anyone here ever run into a similar issue trying to create instances dynamically like this?
2. If so, how did you solve it? Or is it one of those things that just can't be done? Maybe there's some requirement that all instances to be drawn have to be defined at compile time or something? After all, we're talking about a platform that can only handle drawing BMP images (unless you can miraculously get SDL_Image to work, but that's a whole other can of worms lol).
Thanks.
PS: Just out of curiosity, is there a better platform for 2D in C++ than SDL? I'm slowly learning UE4 for 3D, but I mostly play 2D so I figured I'd start with something "simpler" :D