< Go Back
A Clone of Space Invaders written in C++ using SDL2 and SDL_image. Source code is available on Github
- Language: C++
- Libraries: SDL2, SDL_image and SDL_mixer
Implementation
Used SDL2 for 2D rendering and input.
Every object in the game is derived from the Entity class which has Update(), Render() and HandleInputs() virtual functions, These functions can be overriden.
class Entity
{
public:
Entity(const Vector& pos, const std::string& key, const float& scale, const std::string& tag);
virtual ~Entity() = default;
virtual void Update();
virtual void Render(SDL_Renderer* renderer);
virtual void HandleEvents(SDL_Event& event);
virtual bool Destroy();
public:
Vector m_position;
SDL_Rect m_textureRect;
std::string m_tag;
protected:
float m_scale;
SDL_Texture* m_texture;
};
All the game entities are stored in a std::vector
in the Game class and allocated on the heap during game initialization, The Game calls Update(), Render() and HandleInputs() functions for every entity if they have overriden them.
Every object that has collision is derived from the ICollidable interface, And Utils.h has the basic check for AABB collision detection.
class ICollidable
{
public:
virtual ~ICollidable() {}
virtual void OnCollision(ICollidable& otherCollidable) {}
};
The OnCollision() function is just to write the gameplay logic after collision.
Texture Loading
For texture loading I used SDL_image. All the textures are loaded in an unordered_map
in the AssetManager class. The Load() function load textures from the given filePath
with the help of SDL_image’s IMG_LoadTexture function and stores them in the m_assetMap
with the given key
. This function is called during game initialization.
The Get() function returns the texture from the m_assetMap
with the given key
. It is called when an entity is initialized.
class AssetManager
{
public:
AssetManager() = default;
~AssetManager();
AssetManager(const AssetManager&) = delete;
AssetManager& operator=(const AssetManager&) = delete;
static AssetManager& GetInstance();
void Load(SDL_Renderer* renderer, const std::string& key, const std::string& filePath);
SDL_Texture* Get(const std::string& key) const;
SDL_Texture* LoadTexture(SDL_Renderer* renderer, const std::string& key, const std::string& filePath);
private:
std::unordered_map < std::string, SDL_Texture*> m_assetMap;
};
Audio
unordered_map
for storing Mix_Chunk
object which is loaded by the Load() function. The Load() function uses Mix_LoadWAV() function to load Mix_Chunk
from a .wav
file.What I learned
std::unordered_map
. Learned about memory management, all the entities are stored into the heap and the memory is deallocated when necessary.