【发布时间】:2018-02-07 03:34:48
【问题描述】:
我正在用 SFML2 编写一个基于等距图块的简单游戏。地图中的每个瓦片都由瓦片类表示。该类包含 sf::Sprite 对象和 draw() 函数,该函数应该在屏幕上绘制精灵。问题是调用window.draw() 会导致分段错误。我读过它通常是由关联的 sf::Texture 指针无效引起的,但我已经检查过,事实并非如此。
(使用ResourceManager<sf::Texture>对象将纹理引用传递给Tile构造函数)
tile.hpp:
#pragma once
#include <SFML/Graphics.hpp>
#include "resource_manager.hpp"
class Tile
{
public:
Tile(const sf::Texture& texture);
void draw(sf::RenderWindow& window, const float dt);
private:
sf::Sprite _sprite;
};
tile.cpp:
#include "tile.hpp"
Tile::Tile(const sf::Texture& texture)
{
_sprite.setTexture(texture);
}
void Tile::draw(sf::RenderWindow& window, const float dt)
{
std::cout << _sprite.getTexture()->getSize().x << std::endl; //Texture pointer works fine
window.draw(_sprite); //Segmentation Fault here
}
map.hpp:
#pragma once
#include <vector>
#include <SFML/Graphics.hpp>
#include "resource_holder.hpp"
#include "tile.hpp"
class Map
{
public:
Map(ResourceHolder& resources, int width, int height);
void draw(sf::RenderWindow& window, const float dt);
private:
ResourceHolder& _resources;
int _width, _height;
std::vector<Tile> _tiles;
};
map.cpp:
#include "map.hpp"
#include <iostream>
Map::Map(ResourceHolder& resources, int width, int height)
: _resources(resources), _width(width), _height(height)
{
_tiles.reserve(width * height);
for(int y = 0; y < _height; ++y)
{
for(int x = 0; x < _width; ++x)
{
_tiles[x + y * _width] = Tile(_resources.textures["groundTile_NE"]);
}
}
}
void Map::draw(sf::RenderWindow& window, const float dt)
{
for(int x = 0; x < _width; ++x)
{
for(int y = 0; y < _height; ++y)
{
_tiles[x + y * _width].draw(window, dt);
}
}
}
resource_manager.hpp:
#pragma once
#include <unordered_map>
#include <iostream>
template<typename Resource>
class ResourceManager
{
public:
ResourceManager(const std::string& directory, const std::string& extension)
: _directory("assets/" + directory + "/"), _extension("." + extension)
{}
Resource& operator[](const std::string& name)
{
return get(name);
}
Resource& get(const std::string& name)
{
if(!exists(name))
load(name);
return _resources.at(name);
}
bool exists(const std::string& name) const
{
return _resources.find(name) != _resources.end();
}
void load(const std::string& name)
{
Resource res;
if(!res.loadFromFile(_directory + name + _extension))
{
res.loadFromFile(_directory + "_fail_" + _extension);
}
_resources.insert({name, res});
}
private:
const sf::String _directory;
const sf::String _extension;
std::unordered_map<std::string, Resource> _resources;
};
【问题讨论】:
-
@Eddge 它确实返回指针,我的错误
-
@meowgoesthedog 资源是一个模板类型名。在这种情况下是 sf::Texture
-
抱歉,我没有看到模板声明。评论已删除
-
感谢您修复@Hadenir,您能否向我们展示您如何加载纹理以及如何验证它是否正确加载?
-
我已经编辑了问题并添加了执行加载的 map.cpp 和 map.hpp。
_sprite.getTexture()->getSize().x返回正确的宽度,所以我假设纹理加载正确
标签: c++ pointers segmentation-fault sfml