首页 > 解决方案 > 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();

标签: c++sfml

解决方案


您在sprite.

此悬空引用出现在以下行中:

this->tiles[i][j] = Tile(x, y, this->tex[0]);

参考是关于什么的Sprite::setTexture

纹理参数是指只要精灵使用它就必须存在的纹理。事实上,精灵不存储它自己的纹理副本,而是保留一个指向您传递给此函数的那个​​的指针。如果源纹理被破坏并且精灵尝试使用它,则行为未定义。

问题到底出在哪里?

Tile(x, y, this->tex[0]);

在这里,创建了新的实例Tiletex并且sprite是 的成员变量Tile。而spritebysetTexture指的是tex.

tiles[i][j] = Tile(x,...);

在上面的行中,复制赋值运算符被称为从临时对象复制sprite/ tex——由Tile(x,y,..)) 创建。结果,tiles[i][j]您有sprite一个引用临时实例纹理的成员- Tile(..)sprite仅保存指向纹理的指针)。最后,在完整表达式的末尾,临时实例被销毁,texofTile(..)被删除,并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纹理,这是错误的。


推荐阅读