SFML community forums

Help => Graphics => Topic started by: ceeplusplus on April 01, 2020, 11:03:25 pm

Title: Draw shape function
Post by: ceeplusplus on April 01, 2020, 11:03:25 pm
I have this chunk of code that draws a square:

RectangleShape rect (Vector2f(100.f, 100.f));
rect.setFillColor(Color(100, 50, 200));
rect.setPosition(50.f, 50.f);
window.draw(rect);

I want to have some kind of function/class that does this.  The problem I'm having is that when I put this into a function, it doesn't work anymore, because the "window" object is declared inside of main{}.  Is there a way I can pass in the renderwindow from main{} to a function?

full code:
(click to show/hide)

p.s. i'm very new to cpp development, i might be asking the wrong question
Title: Re: Draw shape function
Post by: Hapax on April 02, 2020, 07:24:04 pm
Pass the window by reference (or pointer) to the function.

This is a C++ question more than an SFML one but I shall endeavour to give you a simple example, based on your code, passing by reference:

Function declaration:
void drawRectangle(const sf::RenderWindow& window)
{
    sf::RectangleShape rect (Vector2f(100.f, 100.f));
    rect.setFillColor(Color(100, 50, 200));
    rect.setPosition(50.f, 50.f);
    window.draw(rect);
}

Function call:
drawRectangle(window);