我正在使用 C++ 和 SFML 制作国际象棋游戏。当我尝试在某个类函数中定位纹理加载时,我得到一个白色矩形而不是纹理。这是我的代码:
void GameRender::load_textures(){
Texture texture;
if (!texture.loadFromFile("../graphics/textures/board.png")){
throw;
}
boardSprite.setTexture(texture);
}
void GameRender::draw_board(){
load_textures();
Event event;
Vector2u prevWinSize = window.getSize();
const float desiredAspectRatio = 1.0f / 1.0f;
const float basicScaleX = static_cast<float>(prevWinSize.x) / boardSprite.getGlobalBounds().width;
const float basicScaleY = static_cast<float>(prevWinSize.y) / boardSprite.getGlobalBounds().height;
boardSprite.setScale(basicScaleX, basicScaleY);
while (window.isOpen()){
while (window.pollEvent(event)){
if (event.type == Event::Closed){
window.close();
} else if (event.type == Event::Resized){
set_window_size(desiredAspectRatio, prevWinSize);
}
if (event.type == Event::KeyPressed){
if (event.key.code == sf::Keyboard::Escape){
window.close();
}
}
}
window.clear();
window.draw(boardSprite);
window.display();
}
}
但是,如果我将纹理加载放在draw_board()函数中,它就会按预期工作:
void GameRender::draw_board(){
Texture texture;
if (!texture.loadFromFile("../graphics/textures/board.png")){
throw;
}
boardSprite.setTexture(texture);
Event event;
// remaining code is the same
如何解决这个问题,以便我可以通过在单独的函数中加载纹理来使代码更具可读性?
void sf::Sprite::setTexture(const Texture& texture, bool resetRect = false )
更改精灵的源纹理。纹理参数指的是只要精灵使用它就必须存在的纹理。事实上,精灵并不存储自己的纹理副本,而是保留一个指向您传递给该函数的指针。如果源纹理被破坏并且精灵尝试使用它,则行为是未定义的。
为了解决这个问题,请将
Texture
作为成员变量保留在 GameRender
中,而不是使其成为 load_textures
函数的本地变量。