P16204023
P16204023

Reputation: 1

how do you use a draw function in a different function to the one in which the window was opened?

I am working on a basic game in C++ using SFML for graphics. It is designed to use a grid system with functions to determine what should be displayed in each square. However, the compiler won't recognize the references to the window in the functions.

To keep it easier to expand there are functions for each type of terrain to be displayed, taking the coordinates as inputs (possibly not the correct term).

Upvotes: 0

Views: 71

Answers (1)

arc-menace
arc-menace

Reputation: 475

Good Question. SFML recommends that you create your window in the main function, but, if you want to modify it, you can simply pass it by reference. EX:

#include <SFML/Graphics.hpp>

void doSomething(sf::RenderWindow& window) {
    sf::RectangleShape shape(sf::Vector2f(100, 100));
    shape.setFillColor(sf::Color::Green);
    shape.setPosition(50, 50);
    window.draw(shape);
    window.display();
}

int main() {
    sf::RenderWindow window(sf::VideoMode(500, 500), "Test", sf::Style::Close);
    while (window.isOpen()) {

    sf::Event event;
    while (window.pollEvent(event)) {
        if (event.type == sf::Event::Closed) {
            window.close();
        }
    }

    window.clear(sf::Color::Black);

    //draw here
    doSomething(window);
    }
    return 0;
}

You should take a look at https://www.sfml-dev.org/tutorials/2.5/. Specifically I would look at https://www.sfml-dev.org/tutorials/2.5/window-window.php

Upvotes: 2

Related Questions