我正在尝试制作简单的图块地图。我有一个问题,当设置地图时只有白色正方形。我通常在加载纹理,idk为什么会这样。这是代码:
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();
预先感谢您提供任何有帮助的答案。再次感谢你。 -Tormel
您在sprite
中有悬挂的参考。
此悬挂参考出现在下一行:
this->tiles[i][j] = Tile(x, y, this->tex[0]);
reference对Sprite::setTexture
说什么?
纹理参数是指必须存在的纹理精灵使用它。实际上,该精灵不会存储自己的副本纹理,而是保持指向您传递给的纹理的指针此功能。如果源纹理被破坏并且精灵尝试要使用它,行为是不确定的。
确切在哪里?
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
纹理,这是错误的。