0

I am trying to learn sfml but I cant get over drawing sprite part. Without adding setTextureRect I can see full texture but when I add it, cant see the sprite

#include <SFML/Graphics.hpp>
#include <iostream>

enum directions {down, right, up, left};

int main(){
    unsigned int width = 800;
    unsigned int height = 800;
    sf::RenderWindow *window = new sf::RenderWindow(sf::VideoMode({width, height}), "SFML works!");
    window->setFramerateLimit(60);
    sf::Texture texture;
    if (!texture.loadFromFile("C:\\Game\\assets\\sprites\\SfmlR.png")){
        std::cerr << "Failed to load texture" << std::endl;
        return -1;
    } else {
        std::cout << "Texture loaded successfully" << std::endl;
    }
    sf::Sprite sprite(texture);
    sf::IntRect dir[4];
    for (int i = 0; i < 4; i++){
        dir[i] = sf::IntRect({{ i * 32 , 0}, {32, 32}});
    }
    sprite.setTextureRect(dir[down]);
    sprite.setOrigin({16, 16});
    sprite.setPosition({width /2.f, height / 2.f});
    texture.setSmooth(false);

    while (window->isOpen()){
        while (const std::optional event = window->pollEvent()){
            if (event->is<sf::Event::Closed>())
                window->close();
        }
        if(sf::Keyboard::isKeyPressed(sf::Keyboard::Scan::S)){
            sprite.setTextureRect(dir[down]);
            sprite.move({0, 1});
        } 
        else if(sf::Keyboard::isKeyPressed(sf::Keyboard::Scan::A)){
            sprite.setTextureRect(dir[left]);
            sprite.move({-1, 0});
        }
        else if(sf::Keyboard::isKeyPressed(sf::Keyboard::Scan::W)){
            sprite.setTextureRect(dir[up]);
            sprite.move({0, -1});
        }
        else if(sf::Keyboard::isKeyPressed(sf::Keyboard::Scan::D)){
            sprite.setTextureRect(dir[right]);
            sprite.move({1, 0});
        }
        window->clear();
        window->draw(sprite);
        window->display();
    }
    delete window;
    return 0;
}

its all my code, there is no error but still I cant see the sprite

2
  • 1
    Fwiw, I think the code is fine. I compiled it with a 128x32 png that just contained arrows showing the direction I was moving (with wasd) and it walked around fine and showed the correct arrow in all directions. Commented Mar 10 at 21:02
  • 2
    Sidenote: You don't need new and delete here. Just make window an automatic variable: sf::RenderWindow window(sf::VideoMode({width, height}), "SFML works!"); and then use window. instead of window-> everywhere. Commented Mar 10 at 21:05

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.