SFML/C++ Sprite 由于超出范围而显示为白框,不知道在哪里
SFML/C++ Sprite is being displayed as a white box due to going out of scope, don't know where
标题描述了一切,我正在尝试做一个 tile-based 引擎,但我无法继续,因为我无法找到纹理超出范围的地方。
谢谢。
我的代码:
ImageManager.h
#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;
};
ImageManager.cpp
#include "imageManager.h"
void ImageManager::AddTexture(sf::Texture texture){
textureList.push_back(texture);
}
sf::Texture ImageManager::getIndex(int index) const{
return textureList[index];
}
Tile.h
#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);
};
Tile.cpp
#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);
}
您的构造函数将原始纹理的副本作为参数,该副本在作用域的末尾消失。请改用 (const) 引用。
此外,您的 ImageManager 会在调整其矢量大小时复制纹理,因此所有精灵都将丢失其纹理。使用 std::vector<std::shared_ptr<sf::Texture>>
或使用 Thor 的资源管理器(或实际上任何其他好的库)。
添加到 Hiura 对未来读者的回答中,重要的是要记住 sf::Sprite
只是指向 sf::Texture
的指针以及一些绘图信息。如果 sf::Texture
a sf::Sprite
指向被破坏,sf::Sprite
不再有纹理信息可以使用。正如 Hiura 所说,Tile
的构造函数复制传递给它的 sf::Texture
,将 sf::Sprite
指向副本,然后销毁副本,留下 sf::Sprite
没有 sf::Texture
。通过传递对 sf::Texture
的引用,sf::Sprite
将指向原始 sf::Texture
标题描述了一切,我正在尝试做一个 tile-based 引擎,但我无法继续,因为我无法找到纹理超出范围的地方。
谢谢。
我的代码:
ImageManager.h
#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;
};
ImageManager.cpp
#include "imageManager.h"
void ImageManager::AddTexture(sf::Texture texture){
textureList.push_back(texture);
}
sf::Texture ImageManager::getIndex(int index) const{
return textureList[index];
}
Tile.h
#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);
};
Tile.cpp
#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);
}
您的构造函数将原始纹理的副本作为参数,该副本在作用域的末尾消失。请改用 (const) 引用。
此外,您的 ImageManager 会在调整其矢量大小时复制纹理,因此所有精灵都将丢失其纹理。使用 std::vector<std::shared_ptr<sf::Texture>>
或使用 Thor 的资源管理器(或实际上任何其他好的库)。
添加到 Hiura 对未来读者的回答中,重要的是要记住 sf::Sprite
只是指向 sf::Texture
的指针以及一些绘图信息。如果 sf::Texture
a sf::Sprite
指向被破坏,sf::Sprite
不再有纹理信息可以使用。正如 Hiura 所说,Tile
的构造函数复制传递给它的 sf::Texture
,将 sf::Sprite
指向副本,然后销毁副本,留下 sf::Sprite
没有 sf::Texture
。通过传递对 sf::Texture
的引用,sf::Sprite
将指向原始 sf::Texture