我正在尝试制作一个简单的地图。我有一个问题:设置地图时,只有白色正方形。我通常在加载纹理,所以我不知道为什么会这样。
这是代码:
class Tile
{
private:
sf::Sprite sprite;
sf::Texture tex;
public:
Tile(int x, int y, sf::Texture tex)
{
this->tex = tex;
this->sprite.setTexture(this->tex);
this->sprite.setPosition(x, y);
}
void render(sf::RenderWindow* target)
{
target->draw(this->sprite);
}
class Tilemap
{
private:
Tile tiles[36][64];
sf::Texture tex[4];
public:
//const/dest
Tilemap()
{
this->tex[0].loadFromFile("Resources/Tilemap/Water/water1.png");
int x = -WIDTH+WIDTH/2;
int y = -HEIGTH/2;
for (int i = 0; i < 36; i++)
{
for (int j = 0; j < 64; j++)
{
this->tiles[i][j] = Tile(x, y, this->tex[0]);
x += 60;
}
y += 60;
x = -WIDTH + WIDTH / 2;
}
}
render(sf::RenderWindow* target, sf::Vector2f pos)
{
for (int i = 0; i < 34; i++)
{
for (int j = 0; j < 64; j++)
{
this->tiles[i][j].render(target);
}
}
};
Tilemap map;
map = Tilemap();
最佳答案
您在sprite
中有悬挂的参考。
该悬挂参考出现在下面的行中:
this->tiles[i][j] = Tile(x, y, this->tex[0]);
reference对
Sprite::setTexture
说什么?Texture参数是指必须存在的纹理
精灵使用它。实际上,该精灵不会存储自己的副本
纹理,而是保持指向您传递给的纹理的指针
此功能。如果源纹理被破坏并且精灵尝试
要使用它,行为是不确定的。
问题到底在哪里?
Tile(x, y, this->tex[0]);
在这里,创建了
Tile
的新实例。 tex
和sprite
是Tile
的成员变量。 sprite
的setTexture
是指tex
。tiles[i][j] = Tile(x,...);
在上一行中,调用了复制分配运算符,该运算符从临时对象(由
sprite
创建)复制tex
/ Tile(x,y,..)
。结果,在tiles[i][j]
中,您具有sprite
成员,该成员引用临时实例的纹理-Tile(..)
(sprite
仅保存指向纹理的指针)。最后,在完整表达式的末尾销毁临时实例,删除tex
的Tile(..)
,并且tiles[i][j].sprite
保留指向纹理的无效指针。解?
您必须添加
Tile
的副本构造函数(副本赋值运算符)以正确初始化sprite
来保存其自己的tex
(不引用创建副本的实例):例如:
Tile& operator=(const Tile& theOther)
{
this->tex = theOther.tex;
this->sprite.setTexture(this->tex);
return *this;
}
默认情况下,生成的副本分配运算符
this->sprite
指向theOther.tex
纹理,这是错误的。关于c++ - SFML白色矩形,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/59631899/