最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

c++ - Sfml 3.0.0 setTextureRect does not work as intended - Stack Overflow

programmeradmin4浏览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

发布评论

评论列表(0)

  1. 暂无评论