0
\$\begingroup\$

Why does the drawn Sprite only appear in the Window when drawn from the main-function, but not when drawn from an external function and how can I change this?

class Class {
private: 
sf::Sprite sprite;

public:
Class()
    {
        sprite = initializeSprite(sprite);
    }
};

void Class::draw(sf::RenderWindow& win)
{
    win.draw(sprite);
}

int main(int argc, char* argv[])
{
    sf::RenderWindow window(sf::VideoMode(1920,1080), "Window");
    Class instance;
    while(window.isOpen())
    {
        window.clear();
        instance.draw(window);
        window.display();
    }

    return 0;
}

-> Doesn't work.

int main(int argc, char* argv[])
{
    sf::RenderWindow window(sf::VideoMode(1920,1080), "Window");
    sf::Sprite sprite;
    sprite = initializeSprite(sprite);
    Class instance;
    while(window.isOpen())
    {
        window.clear();
        window.draw(sprite);
        window.display();
    }

    return 0;
}

->Works.

I'm using SFML-2.4.0. It also doesn't work when i use a pointer instead of a reference. What's wrong here?

\$\endgroup\$
1
\$\begingroup\$

I tried out your code and it works quiet fine. How did you initialize your Sprite? One possible reason why it doesn't work is that your image isn't loaded correctly or your sprite is "to small" (that happens if you only says that the color should be red; there is no information about the size so it is 0x0 pixel).

Here is the code I tried (Copy + Paste + Correcting all formal errors):

#include <SFML/Graphics.hpp>

using namespace std;

class Class {

private:

    sf::Sprite sprite;
    sf::Texture texture;

public:

    Class() {
        // Loading my test-image (128x128 px)
        texture.loadFromFile("player.png");
        sprite.setTexture(texture);
    }

    void draw(sf::RenderWindow& win) {
        win.draw(sprite);
    }

};

int main(int argc, char* argv[])
{
    sf::RenderWindow window(sf::VideoMode(640, 480), "Window");
    Class instance;

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

        window.clear();
        instance.draw(window);
        window.display();
    }

    return 0;
}
\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .