Jump to content

  • Log In with Google      Sign In   
  • Create Account


jaeg

Member Since 02 Nov 2011
Offline Last Active Sep 30 2013 12:10 PM
-----

#4879644 Basic Component Based Entity

Posted by jaeg on 02 November 2011 - 06:33 AM

So I've been working on a simple component based entity system so I can create entities on the fly without have to have extreme levels of inheritance. This way if I want an entity to be the player all I have to do is add the appropriate components to let it operate under keyboard control. Another reason I want to try this system out so I can have my AI be able to target anything that has a "targetable component". This way they can destroy props in their way to get to the player.
This is the basic system so far:
CEntity class

class CEntity
{
    public:
        CEntity();
        virtual ~CEntity();

        void addComponent(CComponent*);

        CComponent* getComponentbyName(string);

        void update();
    protected:
    private:
        vector<CComponent*> components;
};



CEntity::CEntity()
{
    //ctor
}

CEntity::~CEntity()
{
    //dtor
}

void CEntity::addComponent(CComponent* newComponent)
{
    components.push_back(newComponent);
}

CComponent* CEntity::getComponentbyName(string name)
{
    for (unsigned int i=0;i<components.size();i++)
    {
        if (name.compare(components[i]->name)==0)
        {
            return components[i];
        }
    }
    return 0;
}

void CEntity::update()
{
    for (unsigned int i=0;i<components.size();i++)
    {
        components[i]->update();
    }
}


CComponent:

class CComponent
{
    public:
        string name;

        CComponent();
        virtual ~CComponent();
        virtual void update()=0;

    protected:
    private:
};


It's not game specific right now since I was just cranking it out last night to see if it even work. The entity will also contain an Irrlicht IAnimatedMeshScene node as well.
I have a factory designed that'll let me create entities based on a name you provide where it'll then proceed to load an external script informing it what components the entity will need. There is also a function that'll create it based on it's node. This is mostly so I can use my level editor which lets me give nodes names. The function takes the node and extracts the name and precedes like the former function.

Is this idea valid or should I be looking at a different way to approach this? The code is really simple right now because I just wanted to get the basic mechanism working before I integrate it into my game engine.


PARTNERS