Search code examples
c++classobjecttexturessfml

Display texture and sprite on the window in class function


So this is my cpp file that has the function. I comment out some member factor as I felt like it wasn't being read at all but will include them to see if I am able to use them. My texture seems to be able to appear but no matter the size or position I try to put it it is not being shown at all. It seems to load properly as I have my if statement to check when it failed to load the texture I want to use. SO what am I doing wrong that is not appearing at all?

//sf::Texture suit::image = suit::setUpTexture();
//
//sf::Texture& suit::setUpTexture()
//{
//    image.loadFromFile("Jester.png");
//    sf::Sprite sprite;
//    sprite.setTexture(image);
//
//    return image;
//}

suit::suit()
{
    sf::Texture image;

    image.loadFromFile("Jester.png");
    sf::Sprite sprite;
    sprite.setTexture(image);
    sf::Sprite::setScale(5,5);

    sprite.setPosition(950,950);

    if(!image.loadFromFile("Jester.png"))
    {
        exit(1);
    }
}

My Header

class suit : public sf::Sprite
{
private:
//    static sf::Texture image;
//    static sf::Texture& setUpTexture();

public:
    suit();
};

Solution

  • When linking an a texture to a sprite, you need to tell that sprite the actual reference to the one texture.

    sprite.setTexture(image&);
    

    Calling the font address by using the '&' operator should solve your problem. You should also load your image only once by calling:

    if(!image.loadFromFile("Jester.png"))
    {
        exit(1);
    }
    

    instead of:

    image.loadFromFile("Jester.png");
    

    I Actually don't know if you did it after relooking at your code, but do not forget to draw your actor using the draw() method.