Welcome, Guest. Please login or register. Did you miss your activation email?

Author Topic: One function to clear, draw, and display the window?  (Read 2499 times)

0 Members and 2 Guests are viewing this topic.

dd

  • Newbie
  • *
  • Posts: 10
    • View Profile
One function to clear, draw, and display the window?
« on: January 01, 2024, 05:07:28 pm »
Hi, I'm currently developing a game using SFML, and to make my code look better I was wondering if I could somehow make one function to clear, draw on, and display the window without having to list each object I want to draw as a separate parameter.
Thanks!

kojack

  • Sr. Member
  • ****
  • Posts: 343
  • C++/C# game dev teacher.
    • View Profile
Re: One function to clear, draw, and display the window?
« Reply #1 on: January 02, 2024, 01:53:59 am »
What you will need to do is store all of the things you want to draw in a container (like vector or map), so the render function can loop over them.

For example, you could have a base GameObject class with virtual methods for updating and rendering.
class GameObject
{
public:
   virtual void update(float deltaTime) = 0;
   virtual void render(sf::RenderWindow &rw) = 0;
};

std::vector<GameObject*> objects;

The rendering code could then be like:
void renderGame(sf::RenderWindow &rw)
{
   rw.clear();
   for(GameObject *obj : objects)
   {
      obj->render(rw);
   }
   rw.display();
}

Now you can inherit from GameObject to make your concrete classes (player, enemies, etc). They can have sprites that they draw (or other things like text, etc). Add them to the vector for them to be rendered.
The update function isn't actually needed here, but you might as well move game logic into the class too in the same way rendering has been.

dd

  • Newbie
  • *
  • Posts: 10
    • View Profile
Re: One function to clear, draw, and display the window?
« Reply #2 on: January 02, 2024, 06:37:13 pm »
This worked great, thanks!