SFML白色矩形 [英] SFML white rectangle

查看:221
本文介绍了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]);

reference关于Sprite::setTexture说了什么?

纹理参数引用的纹理必须存在于 精灵使用它。事实上,精灵并没有存储它自己的副本 纹理,而是保留指向您传递到的纹理的指针 此函数。如果源纹理被破坏,而精灵尝试 若要使用它,行为是未定义的。

问题具体在哪里?

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

这里创建了Tile的新实例。texspriteTile的成员变量。spritebysetTexture指的是tex

tiles[i][j] = Tile(x,...);
在上面的行中,调用了复制赋值操作符,该操作符从临时对象复制sprite/tex,由Tile(x,y,..)创建)。因此,在tiles[i][j]中,您有sprite成员,它引用临时实例的纹理-Tile(..)(sprite只持有指向纹理的指针)。最后,在完整表达式的末尾销毁临时实例,删除Tile(..)tex,并且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纹理,这是错误的。

这篇关于SFML白色矩形的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆