簡體   English   中英

我的sfml ImageManager類在C ++中僅顯示白色正方形

[英]My sfml ImageManager class is only displaying a white square in c++

我知道這個話題在論壇中很豐富,但是對於這個特定問題我需要幫助。 我正在按照本教程制作井字游戲的基本sfml ImageManager類。 我在理解如何在游戲引擎中實現此類時遇到了麻煩。 我將發布很多代碼,因為其中涉及多個類:Board.h:我的井字游戲板。

#pragma once
#include "stdafx.h"
#include <vector>
#include "Box.h"
#include "SFML/Graphics.hpp"
#include "ImageManager.h"

class Board{
public:
Board();
~Board();

std::vector<Box> &GetBoxes();

sf::Sprite GetGameBoard();
private:
sf::Sprite gameBoard;

std::vector<Box> boxes;
};

這是Board.cpp:

#include "stdafx.h"
#include "Board.h"
#include "SFML/Graphics.hpp"

Board::Board(){
ImageManager imgr;
imgr.AddResourceDirectory("images/");
gameBoard.setTexture(imgr.GetImage("images/t3board.png"));
}

Board::~Board(){

}

std::vector<Box> &Board::GetBoxes(){
return boxes;
}

sf::Sprite Board::GetGameBoard(){
return gameBoard;
}

這是本教程的ImageManager類中的相關內容:

const sf::Texture &ImageManager::GetImage(const std::string &filename){
    for(std::map<std::string, sf::Texture>::const_iterator it = textures_.begin(); it != textures_.end(); ++it){
        if(filename == it->first){
            std::cout << "DEBUG_MESSAGE: " << filename << " using existing image.\n";
            return it->second;
        }
    }

    //if image doesn't exist (no need for else since it will return if filename is found
    sf::Texture texture;
    if(texture.loadFromFile(filename)){
        //create both a string and matching image in the map
        textures_[filename] = texture;
        std::cout << "DEBUG_MESSAGE: " << filename << " loading image.\n";
        return textures_[filename];
    }

    // If the image has still not been found, search all registered directories
    //of course, it will be empty until I specify extra directories by adding them into the vector
    for(std::vector< std::string >::iterator it = resourceDirectories_.begin(); it != resourceDirectories_.end(); ++it){
        if(texture.loadFromFile((*it) + filename )){
            textures_[filename] = texture;
            std::cout << "DEBUG_MESSAGE: " << filename << " loading image 2.\n";
            return textures_[filename];
        }
    }

    //again, notice there's no elses because returns serve as breaks
    std::cout << "GAME_ERROR: Image was not found. It is filled with an empty image.\n";
    textures_[filename] = texture;
    return textures_[filename];
}

最后,在引擎中,我獲得gameBoard並將其繪制到我的窗口中:

void Engine::Render(){
    window.clear();
    window.draw(board.GetGameBoard());
    window.display();
}

我的窗口僅顯示完整的白色背景,但否則仍然可以使用。 有人可以看到我做錯了嗎?

我假設textures_ImageManager類的私有成員? 在那種情況下,您有未定義的行為,因為ImageManager::GetImage返回對存儲在已銷毀的容器中的數據的引用 (請記住imgr是構造函數中的局部變量)。

好吧,我有。 這是一個非常尷尬的解決方案,但是在Board的構造函數中聲明ImageManager imgr Board立即破壞ImageManager,因此我只剪切了該實例並將其粘貼在頭文件中。 出於某種原因,有必要返回一個參考而不是實際的紋理值,這也讓我很沮喪。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM