我試圖將所有紋理存儲在數組中。但圖像沒有得到返回它似乎這裏是我的代碼C++無法返回sf :: Texture
我假設我的loadTex和loadSpri函數將返回並將他們的數據存儲在我所做的數組中,但它似乎不是這樣工作,因爲當我運行遊戲他們不出現,只是空白。我的代碼可能很糟糕,但我很初學者還是並試圖獲得的東西
掛起這裏的render.cpp
#include "render.h"
texandsprite render::textures[5];
sf::Texture loadTex(std::string);
sf::Sprite loadSpri(sf::Texture);
//Function to start the game
void render::start()
{
_mainWindow.create(sf::VideoMode(1024, 768, 32), "A New Life");
textures[1].tex = loadTex("civilian.png");
textures[1].spri = loadSpri(textures[1].tex);
GameLoop();
}
void render::GameLoop()
{
sf::Event event;
//Load(1, "civilian.png");
float x = 0;
float y = 0;
while(_mainWindow.isOpen())
{
while (_mainWindow.pollEvent(event))
{
//Check the type of event
switch (event.type)
{
//window closed
case sf::Event::Closed:
_mainWindow.close();
break;
case sf::Event::KeyPressed:
switch(event.key.code)
{
case sf::Keyboard::Up:
--y;
break;
case sf::Keyboard::Down:
y += 5;
break;
case sf::Keyboard::Right:
++x;
break;
case sf::Keyboard::Left:
--x;
break;
}
break;
default:
break;
}
}
_mainWindow.clear(sf::Color::White);
//Draw everything here
//_mainWindow.draw(...);
textures[1].spri.setPosition(x,y);
_mainWindow.draw(textures[1].spri);
//End the current frame
_mainWindow.display();
}
}
sf::RenderWindow render::_mainWindow;
sf::Texture render::loadTex(std::string filename)
{
sf::Texture temptex;
if(!temptex.loadFromFile(filename))
{
std::cout << "Error: could not load image" << filename << std::endl;
}
std::cout << filename << " Loaded" << std::endl;
return temptex;
}
sf::Sprite render::loadSpri(sf::Texture temptex)
{
sf::Sprite tempspri;
tempspri.setTexture(temptex);
return tempspri;
}
這裏的render.h
#ifndef RENDER_H_INCLUDED
#define RENDER_H_INCLUDED
#include "SFML/Window.hpp"
#include "SFML/Graphics.hpp"
#include <iostream>
struct texandsprite
{
sf::Texture tex;
sf::Sprite spri;
};
class render
{
public:
static void start();
//Here will go a list of all moving entities
static texandsprite textures[5];
//Here will go a list of all nonmoving entities
//static
private:
static void GameLoop();
static void Rendering();
static sf::Texture loadTex(std::string);
static sf::Sprite loadSpri(sf::Texture);
static sf::Texture texture;
static sf::Sprite sprite;
static sf::RenderWindow _mainWindow;
};
#endif // RENDER_H_INCLUDED
我知道白方的問題,我想我知道爲什麼發生了。是因爲當你在一個函數中創建紋理時,它只是在本地爲該函數創建的,所以當該函數結束時,分配給它的資源被釋放了嗎?這是正確的嗎?你能給我一個代碼示例,我不完全理解你會怎麼做呢?謝謝 – Joshua
@Joshua是的,就是這樣。我已更新我的答案以回答您的評論。 ;-) – Hiura