SFML/C++ 雪碧因超出范围而被显示为白框,不知道在哪里

SFML/C++ Sprite is being displayed as a white box due to going out of scope, don't know where

本文关键字:显示 白框 在哪里 不知道 范围 C++ SFML      更新时间:2023-10-16

标题描述了一切,我试图做一个基于瓷砖的引擎,但我不能继续,因为我只是找不到纹理超出范围的地方。

谢谢。我代码:

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::Sprite指向的sf::Texture被破坏,sf::Sprite就不再有纹理信息可以使用。正如Hiura所说,Tile的构造函数复制传递给它的sf::Texture,将sf::Sprite指向副本,然后销毁副本,留下没有sf::Texturesf::Sprite。通过传递对sf::Texture的引用,sf::Sprite将指向原来的sf::Texture