実際、あなたの質問はSDLを直接参照せずに答えることができ、同じ問題がどのライブラリ(sfmlなど)でも発生する可能性があり、解決策はすべてほぼ同じです。答えは、あなたのテクスチャからシングルトンのデザインパターンです。なぜ私はシングルトンと言うのですか?壁のタイルについて話しましょう。数千またはそれ以上の壁タイルがすべて同じテクスチャである場合、各壁ごとに何度も何度もロードする必要がありますか? 番号。それは同じテクスチャです。特定のテクスチャごとに1 つのインスタンスが必要です。さらに: すべてを含むスプライト シートを使用するか、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 オブジェクトを処理してレンダリングする場合、シングルトンでは不十分であることがわかり、「flyweight」設計パターン全体を参照できます。 gameprogrammingpatterns.com と伝説的な本: Design Patterns: Elements of Reusable Object-Oriented Software の 2 つを読むことをお勧めします。
コードに存在するコードの問題がいくつかあります。スイッチケースの動き。「突然追加のアクションを追加したい場合はどうなりますか?」と自問してください。「たとえば、前の動きに応じて異なる動作をさせたい場合はどうしますか?」あなたのアプローチは、大規模で長いスイッチケースにつながります。どちらも、コードをより簡単に変更できるようにする方法を示します