0
\$\begingroup\$

This question is probably well documented but I can't find any resources.

Basically I'm not sure how to structure rendering with SDL in my code.

I made a render class which calls the api and the game loop contains this:

while(running) {
    renderer->RenderClear();
    map->DrawMap();
    player->render();
    renderer->RenderPresent();
}

Everything is rendering properly however I'm not sure how I should structure my code if there's many more things that need rendering. I want to draw a box on the screen with SDL_RenderDrawLine but the line will only draw for one frame before RenderPresent in the main loop clears it. I don't think I should have everything placed in the loop that may need rendering.

What is the proper code structure in which objects should use the render api? An array which contains everything to render in the loop? Separate instances of Render() which call their own draw and render? Something else?

\$\endgroup\$
2
\$\begingroup\$

Everything has to be in the loop, otherwise they can't be rendered. The question is, should they be there by themselves or hidden behind function/classes? This is an organisation question, as in, all results work, but what's "better" depends on you.

One way to solve this, is to have an abstract class that implements some functions like update and draw. This class represents a "Scene" inside your game. It can represent the main menu, or the character selection screen, etc. Now create subclasses for each of these scenes, that implement those functions and now how to draw themselves.

Now create one object, with the type of the abstract class, and initialise it with one of the subclasses. That object is the current scene of your game. Each loop iteration, call its update and then its draw functions. Whenever the user does a specific action (for example select "start game" from the main menu), re-initialise this object with another subclass of the appropriate scene. Your loop doesn't need to change, and now the new scene is being updated/drawn.

Note that this is not the only way to do this, but as far as I know its quite well-known. There might be better ways out there, but that's up to you to experiment and find the right one for you.

\$\endgroup\$

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.