c++ - SFML 白色矩形
问题描述
我正在尝试做一个简单的瓷砖地图。我有一个问题:当我设置地图时,只有白色方块。我通常加载纹理,所以我不知道为什么会这样。
这是代码:
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]);
参考是关于什么的Sprite::setTexture
?
纹理参数是指只要精灵使用它就必须存在的纹理。事实上,精灵不存储它自己的纹理副本,而是保留一个指向您传递给此函数的那个的指针。如果源纹理被破坏并且精灵尝试使用它,则行为未定义。
问题到底出在哪里?
Tile(x, y, this->tex[0]);
在这里,创建了新的实例Tile
。tex
并且sprite
是 的成员变量Tile
。而sprite
bysetTexture
指的是tex
.
tiles[i][j] = Tile(x,...);
在上面的行中,复制赋值运算符被称为从临时对象复制sprite
/ tex
——由Tile(x,y,..)
) 创建。结果,tiles[i][j]
您有sprite
一个引用临时实例纹理的成员- Tile(..)
(sprite
仅保存指向纹理的指针)。最后,在完整表达式的末尾,临时实例被销毁,tex
ofTile(..)
被删除,并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
纹理,这是错误的。
推荐阅读
- python - z 轴的非线性颜色范围
- postgresql - 从 Oracle SQL 转换 Postgres
- c# - 异步方法运行速度太快,无法在主线程上更新我的列表框
- node.js - 赛普拉斯永远不会通过 Windows 上的加载屏幕
- sql - Redshift 中的每月计数行 - 如何在没有活动的月份的结果中包含 0 行
- python - 如何使用计数查找列的范围间隔并比较其值?
- reactjs - 使用 postgres PRN 堆栈在表格中格式化日期
- c - 带有共享测试问题目录的 Makefile
- javascript - 如何使用根节点项按顺序遍历嵌套 JSON
- rest - 如何在 odata 表达式中执行空值合并?