I'm making a game engine and currently I'm working on Entity Component System. Here is some code for better understanding:
class Entity {
public:
...
void AddComponent(EntityComponent component, unsigned int id){
m_Components.insert({id, component});}
EntityComponent GetComponent(unsigned int id)
{
auto i = m_Components.find(id);
ASSERT(i != m_Components->end()); // ASSERT is a custom macro
return i->second;
}
private:
...
std::unordered_map<unsigned int, EntityComponent> m_Components;
};
Also a simple parent class EntityComponent, that deals only with IDs (I skipped some code, because it doesn't matter in this problem):
class EntityComponent {
public:
...
private:
unsigned int m_EntityID;
size_t m_PoolIndex;
};
And it's children. One of them would be a TransformComponent:
class TransformComponent : public EntityComponent {
public:
TransformComponent(unsigned int entityID, unsigned int poolID = 0, glm::vec2 position = glm::vec2(1.0,1.0), glm::vec2 scale = glm::vec2(1.0,1.0), float rotation = 0) : EntityComponent(entityID, poolID),m_Rotation(rotation), m_Scale(scale), m_Position(position){}
inline glm::vec2 GetPosition() { return m_Position; }
inline glm::vec2 GetScale() { return m_Scale; }
private:
glm::vec2 m_Position;
float m_Rotation;
glm::vec2 m_Scale;
};
So the problem is that I want to create an Entity, add a TransformComponent to it and use its functions GetPosition(), GetScale().
Creating an entity and adding TransformComponent works, but when I want to use GetComponent(id) it returns the parent class EntityComponent, so it means that I cannot use functions like GetPosition() etc.
How can I change the code, so I can add different children of EntityComponent to the unordered_map and receive them using their ID and use their public methods?