informative
informative

Reputation: 53

SFML window.draw(); only shows up for a small time

I'm attempting to get a picture to display by using SFML (just a test run). The program can find the picture, and open a new window, but when it opens the window it only pops up for half a second then returns with 1. Here is the code (which is just their example that I tweaked):

#include <SFML/Graphics.hpp>

int main()
{
    sf::RenderWindow window(sf::VideoMode(500, 500), "SFML works!");

    sf::Texture Texture;
    sf::Sprite Sprite;
    if(!Texture.loadFromFile("resources/pepe.png"));
        return 1;

    Sprite.setTexture(Texture);

    while (window.isOpen())
    {
        sf::Event event;
        while (window.pollEvent(event))
        {
            if (event.type == sf::Event::Closed)
                window.close();
        }
        window.clear();
        window.draw(Sprite);
        window.display();
    }

    return 0;
}

I am assuming the error is coming from the return 1; after the loading, but I don't see what is wrong. Can someone post something that worked for them or give me tips on what may be going wrong?

Upvotes: 1

Views: 814

Answers (1)

Emile Bergeron
Emile Bergeron

Reputation: 17430

Your code works just fine, except for the ; after the texture loading from a file, making your program always return 1, whatever was happening before.

It's a good idea to add error messages to know what's going wrong.

#include <SFML/Graphics.hpp>

#include <iostream>
int main()
{
    sf::RenderWindow window(sf::VideoMode(500, 500), "SFML works!");

    sf::Texture Texture;
    sf::Sprite Sprite;
    if(!Texture.loadFromFile("resources/pepe.png")){ // there was a ; here.
        // making the code below always run.
        std::cerr << "Error loading my texture" << std::endl;
        return 1;
    }

    Sprite.setTexture(Texture);

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

            // you only get here when there is at least one event. 
        }

        // but you always want to display to the screen.
        window.clear();
        window.draw(Sprite);
        window.display();

    }

    return 0;
}

My rule of thumb is to always enclose code blocks with curly braces so you never make these kind of mistakes (or someone else changing your code is less prone to make that mistake).

Upvotes: 3

Related Questions