I'm trying to implement a component based design for a game I'm making. I decided to write it in C++, but I'm not very good at it. Coming from a Java background I encountered a problem when trying to manage the std::vector
for the components. Right now each entity has a vector of components that can be of different derived classes such as "Transform Component" which has an x
and y
field that I will access later. From what I've read I have to use a std::shared_ptr
for each component, and that has worked fine except when I retrieve a component and try to cast it I start getting errors.
The code looks like this:
Component.hpp
class Component
{
public:
virtual ComponentType getType() = 0;
virtual ~Component() { }
};
Transfrom.hpp
class Transform : public Component
{
public:
float x, y;
virtual ComponentType getType() { return ComponentType::TRANSFORM; }
};
Entity.hpp
class Entity
{
public:
Entity() : m_components() { }
Component& getComponent(ComponentType type);
void addComponent(std::shared_ptr<Component> comp);
bool hasComponent(ComponentType type);
private:
std::vector<std::shared_ptr<Component>> m_components;
};
And when I try to use it:
// This gives an error!
Transform comp = std::dynamic_pointer_cast<Transform>(entity.getComponent(ComponentType::TRANSFORM));
How can I fix this?
typeid
you could do something like this:template<typename T> hasComponent() { for (auto comp : components) if (typeid(comp)) == typeid(T) return true; return false; }
so you could simply do:if (entity_manager.doesEntityHaveComponent<SomeComponent>(id)) { .... }
'. – LiquidFeline Jul 29 '15 at 15:55