由于超出范围,SFML/C++Sprite显示为白色框,不知道在哪里

由于超出范围,SFML/C++Sprite显示为白色框,不知道在哪里,c++,scope,sfml,C++,Scope,Sfml,标题描述了一切,我正在尝试做一个基于平铺的引擎,但我无法继续,因为我无法找到纹理超出范围的地方 多谢各位 我的代码: 图像管理器 #pragma once #include <SFML/Graphics.hpp> #include <vector> class ImageManager{ std::vector<sf::Texture> textureList; public: void AddTexture(sf::Texture);

标题描述了一切,我正在尝试做一个基于平铺的引擎,但我无法继续,因为我无法找到纹理超出范围的地方

多谢各位

我的代码:

图像管理器

#pragma once

#include <SFML/Graphics.hpp>
#include <vector>

class ImageManager{
    std::vector<sf::Texture> textureList;
public:

    void AddTexture(sf::Texture);
    sf::Texture getIndex(int index) const;
};
瓦片

#pragma once

#include <SFML/Graphics.hpp>
#include <memory>

class Tile{
    sf::Sprite sprite;

public:
    Tile(sf::Texture texture);

    void draw(int x, int y, sf::RenderWindow* rw);
};

构造函数将原始纹理的一个副本作为参数,该副本在作用域的末尾消失。改用常量引用


此外,当调整向量大小时,ImageManager将复制纹理,因此所有精灵将丢失其纹理。可以使用std::vector,也可以使用的资源管理器或任何其他好的库。

您的构造函数将在作用域末尾消失的原始纹理的副本作为参数。改用常量引用


此外,当调整向量大小时,ImageManager将复制纹理,因此所有精灵将丢失其纹理。可以使用std::vector,也可以使用的资源管理器或任何其他好的库。

除了Hiura的答案之外,还有一点很重要,那就是要记住sf::Sprite只是指向sf::纹理的指针以及一些绘图信息。如果sf::Sprite指向的sf::纹理被破坏,则sf::Sprite不再具有可处理的纹理信息。正如Hiura所说,Tile的构造函数复制传递给它的sf::Texture,将sf::Sprite指向副本,然后销毁副本,使sf::Sprite没有sf::Texture。通过传递对sf::Texture的引用,sf::Sprite将指向原始sf::Texture

添加到Hiura的答案中供未来读者阅读,记住sf::Sprite只是指向sf::Texture的指针以及一些绘图信息,这一点很重要。如果sf::Sprite指向的sf::纹理被破坏,则sf::Sprite不再具有可处理的纹理信息。正如Hiura所说,Tile的构造函数复制传递给它的sf::Texture,将sf::Sprite指向副本,然后销毁副本,使sf::Sprite没有sf::Texture。通过传递对sf::Texture的引用,sf::Sprite将指向原始sf::Texture

这似乎是一种问题,它将真正受益于一个新的sf::Texture。@Nathantugy好的,完成。我认为添加完整的代码会有所帮助,因为它是实际的可编译代码,但如果这4个文件足够,那就太好了。谢谢你。这似乎是一个真正能从一个项目中受益的问题。@Nathantugy好的,完成了。我认为添加完整的代码会有所帮助,因为它是实际的可编译代码,但如果这4个文件足够,那就太好了。非常感谢。
#pragma once

#include <SFML/Graphics.hpp>
#include <memory>

class Tile{
    sf::Sprite sprite;

public:
    Tile(sf::Texture texture);

    void draw(int x, int y, sf::RenderWindow* rw);
};
#include "Tile.h"

Tile::Tile(sf::Texture texture){
    sprite.setTexture(texture);
}

void Tile::draw(int x, int y, sf::RenderWindow* rw){
    sprite.setPosition(x, y);
    rw->draw(sprite);
}