Carregar uma textura no SFML falha sem nenhuma mensagem sobre o porquê

StackOverflow https://stackoverflow.com/questions/19855730

  •  29-07-2022
  •  | 
  •  

Pergunta

Eu tenho acompanhado os tutoriais no SFML e tentei carregar uma textura usando o seguinte código

sf::Texture texture;
if (!texture.loadFromFile("image.png"))
{
    return sf::Texture();
}

Isso falha em carregar a textura, o sprite é branco, que não é a cor do meu sprite.

Foi útil?

Solução

Como retirado diretamente do tutorial gráfico-sprite no site da SFML

"The loadFromFile function sometimes fails with no obvious reason. First, check the error message printed by SFML in the
standard output (check the console). If the message is unable to open file, make sure that the working directory (which is the
directory any file path will be interpreted relatively to) is what you think it is: when you run the application from the explorer, the
working directory is the executable folder, but when you launch your program from your IDE (Visual Studio, Code::Blocks, ...) the
working directory is sometimes set to the project directory instead. This can generally be changed easily in the project settings." 

Portanto, verifique se a sua imagem é nomeada em primeiro lugar corretamente e, em segundo lugar, verifique se está na pasta correta, ou seja, no seu diretório de trabalho.

Além disso, se a textura não carregar em vez de retornar um sprite vazio, você poderá relatar um erro ao console e depois lançar uma exceção. Dessa forma, você será informado de que o sprite não carrega corretamente e o programa terá que lidar com a exceção, caso contrário, será encerrado. Dessa forma, nenhum sprite no jogo deve ter uma textura branca, a menos que seja intencional

Algo assim:

sf::Texture texture;
if (!texture.loadFromFile("image.png"))
{
    throw std::runtime_error("Could not load image.png");
}

Outras dicas

Carregando um PNG? Faça 8 bits. Outros formatos PNG podem ser carregados, mas sempre são exibidos como quadrados brancos.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top