【发布时间】:2020-11-07 16:24:07
【问题描述】:
我在使用 C++ 和 SFML 库编写纸牌游戏时遇到了问题。当我执行应用程序时,没有显示卡片纹理,我看到的唯一的东西是白色矩形或卡片的纹理以一种奇怪的方式扭曲。 我已经搜索了所有可能的页面,但没有找到答案。为什么这些纹理有时会出现并闪烁?为什么又出现了白色矩形? 我发现的是:这是由于缺少纹理。事实上,我使用纹理作为对象的属性。因此,只要它们需要通过 SFML 渲染函数渲染到屏幕上,它们就在内存中。 因此,我的代码中一定存在某种缺陷。我有以下几行代码(老实说,还有更多代码。我提取了这些行来提供这里重要的内容):
Card.cpp
class Card {
public:
static std::string textureDirectory;
Card(unsigned int id);
void render(sf::RenderWindow &window);
private:
unsigned int id;
sf::Sprite background;
sf::Texture texture;
void loadTexture();
};
std::string Card::textureDirectory = "media/textures/cards/";
void Card::render(sf::RenderWindow &window){
window.draw(this->background);
}
void Card::loadTexture(){
std::string extension = ".png";
std::string cardIdAsString = std::to_string(this->id);
if (!this->texture.loadFromFile( Card::textureDirectory + cardIdAsString + extension ))
std::cout << "Couldn't load the texture: " << cardIdAsString << extension;
}
Card::Card(unsigned int id){
this->id = id;
this->loadTexture();
}
Character.cpp
class Character {
private:
std::vector <Card> deck;
public:
Character();
void renderCards(sf::RenderWindow& window);
private:
void createDeck();
void addToDeckCardWithId(unsigned int id);
};
void Character::addToDeckCardWithId(unsigned int id){
this->deck.push_back( Card(id) );
}
void Character::createDeck(){
this->addToDeckCardWithId(0);
this->addToDeckCardWithId(0);
}
Character::Character(){
this->createDeck();
}
void Character::renderCards(sf::RenderWindow& window){
int size = this->deck.size();
for (int i = 0; i<size; i++)
this->deck.at(i).render(window);
}
所有纹理都已正确加载,因此加载它们不是问题。 提前致谢!
【问题讨论】:
标签: c++ vector memory-management textures sfml