实际上,您的问题可以在不直接参考 SDL 的情况下得到回答,并且任何库(如 sfml)都可能出现相同的问题,并且解决方案大致相同:答案是单例设计模式,因为您的纹理为什么我说单例?让我们谈谈墙砖。您可能有数千甚至更多的墙砖都具有相同的纹理,您真的想在每面墙上一次又一次地加载它吗?不。这是相同的纹理,您希望每个给定纹理都有一个实例,甚至更多:如果您使用包含所有内容的精灵表或假设有 3 张表,则可以节省资源工作:这是 sfml 中的一个示例,尽管想法应该是在 SDL 中也是如此。
https://en.wikipedia.org/wiki/Singleton_pattern
这是一个 sfml 实现,但其背后的想法应该清晰且易于模仿:
class Resources {
sf::Clock m_clock; //holds clock
sf::Texture m_soma,m_lvl,m_enemies; //holds hero,lvl &enemies textures respectively
sf::Font m_font; //holds game font
Resources();
public:
~Resources() {}
Resources(const Resources &) = delete;
Resources& operator=(const Resources &) = delete;
static Resources& instance();
sf::Texture& texture();
sf::Texture& lvlTexture();
sf::Texture& Enemies();
sf::Clock& clock();
sf::Font & Font();
};
cpp 文件:注意我可以使用矢量而不是 3 个纹理
Resources::Resources()
{
//loading textures(hero,lvls,enemies)
if (!m_soma.loadFromFile("..\\resources\\sprites\\soma.png"))
{
std::cerr << "problem loading texture\n";
throw ResourceExceptions("couldn't load player sprites!: must have ..\\resources\\sprites\\soma.png");
}
if (!m_lvl.loadFromFile("..\\resources\\sprites\\lv.png"))
{
std::cerr << "problem loading texture\n";
throw ResourceExceptions("couldn't load level sprites!: must have ..\\resources\\sprites\\lv.png");
}
if (!m_enemies.loadFromFile("..\\resources\\sprites\\enemies.png"))
{
std::cerr << "problem loading texture\n";
throw ResourceExceptions("couldn't load enemies sprites!: must have ..\\resources\\sprites\\enemies.png");
}
//loading font once
if (!m_font.loadFromFile("..\\resources\\font\\gothic.otf"))
{
std::cerr << "problem loading font\n";
throw ResourceExceptions("couldn't load game Font: must have ..\\resources\\font\\gothic.otf");
}
}
Resources & Resources::instance()
{
static Resources resource;
return resource;
}
sf::Texture & Resources::texture()
{
return m_soma;
}
sf::Texture & Resources::lvlTexture()
{
return m_lvl;
}
sf::Texture & Resources::Enemies()
{
return m_enemies;
}
sf::Clock & Resources::clock()
{
return m_clock;
}
sf::Font & Resources::Font()
{
return m_font;
}
例如。用法是: m_sprite.setTexture(Resources::instance().texture());
//----------------------------------------
同样的想法可以应用到任何地方,甚至更多,如果你有机会处理 3d 对象并渲染那些你会发现单例甚至不够,你可以参考“轻量级”设计模式我建议您阅读两本书:gameprogrammingpatterns.com 和传奇书籍:Design Patterns: Elements of Reusable Object-Oriented Software
您的代码中存在几个代码问题:例如。开关盒上的运动。问问自己“如果我突然想添加一个额外的动作会发生什么?” “例如,如果我希望它根据之前的动作表现不同怎么办?” 您的方法将带您进行广泛而漫长的开关案例。两者都会向您展示可以让您更轻松地更改代码的方法