Alex Rivera | Logout

Handling entities in a game

Asked 2010-11-06T10:57:46.023
12

As a small exercise I am trying to write a very small, simple game engine that just handles entities (moving, basic AI etc.)

As such, I am trying to think about how a game handles the updates for all of the entities, and I am getting a little bit confused (Probably because I am going about it in the wrong way)

So I decided to post this question here to show you my current way of thinking about it, and to see if anyone can suggest to me a better way of doing it.

Currently, I have a CEngine class which take pointers to other classes that it needs (For example a CWindow class, CEntityManager class etc.)

I have a game loop which in pseudo code would go like this (Within the CEngine class)

while(isRunning) {
    Window->clear_screen();

    EntityManager->draw();

    Window->flip_screen();

    // Cap FPS
}

My CEntityManager class looked like this:

enum {
    PLAYER,
    ENEMY,
    ALLY
};

class CEntityManager {
    public:
        void create_entity(int entityType); // PLAYER, ENEMY, ALLY etc.
        void delete_entity(int entityID);

    private:
        std::vector<CEntity*> entityVector;
        std::vector<CEntity*> entityVectorIter;
};

And my CEntity class looked like this:

class CEntity() {
    public:
        virtual void draw() = 0;
        void set_id(int nextEntityID);
        int get_id();
        int get_type();

    private:
        static nextEntityID;
        int entityID;
        int entityType;
};

After that, I would create classes for example, for an enemy, and give it a sprite sheet, its own functions etc.

For example:

class CEnemy : public CEntity {
    public:
        void draw(); // Implement draw();
        void do_ai_stuff();

};

class CPlayer : public CEntity {
    public:
        void draw(); // Implement draw();
        void handle_input();
};
Edit
Report

1 Answer

7

You could realize this functionality by using virtual function as well:

class CEntity() {
    public:
        virtual void do_stuff() = 0;
        virtual void draw() = 0;
        // ...
};

class CEnemy : public CEntity {
    public:
        void do_stuff() { do_ai_stuff(); }
        void draw(); // Implement draw();
        void do_ai_stuff();

};

class CPlayer : public CEntity {
    public:
        void do_stuff() { handle_input(); }
        void draw(); // Implement draw();
        void handle_input();
};
answered 2010-11-06T11:03:15.667

Your Answer