I'm a fairly experienced programmer, but I'm still relatively new to OOP architecture and design in c++. Most of my experience is with C# and Java. I recently endeavored to code up a simple game engine in c++. I used SDL for the graphics. In this post, I would like to discuss my architecture and to get some feedback on it. Particularly, I've run into a design issue that I would like some help with. So, here goes:
My problem is this:
I tried to do a kind of interface-style design. It involves a series of
abstract base classes that allow each object to implement a behavior. For example, if I want an object to be movable,
it would have to inherit from the movable base class which contains a virtual function called move()
and some position
coordinates. If I wanted it to be collidable, the object would inherit from the collidable abstract class, which
contains the virtual functions checkCollision()
and handleCollision()
as well as a hitbox member variable. An object
like the player inherits from both of these base classes as well as several others.
This works well enough as long as I'm doing everything by hand in the main loop. I can just say:
player.move();
player.checkCollision();
player.handleCollision();
player.draw().
and it's fine. But I would like to be able to have a vector or array of generic objects in the main loop and do something like this:
for each object in vector
if object is of type movable
object.move();
if object is of type collidable
object.checkCollision();
I thought that I could accomplish this with dynamic casting, but I really haven't been able to come up with anything. I've tried storing them as void pointers, but that doesn't work the way I want it to. I've been reading about this gameobject-component architecture for video games that I might try, but I'd really like to salvage what I've already written. I figure this is a good learning opportunity. If anybody has any ideas I'd really appreciate it. How does my architecture compare to other simple game engine designs? does my interface architecture make sense or is it totally wonky?
If you work in C++, try SFML, it's faster than SDL, and if you know OpenGL, you can use it too.
For your problem:
class Entity {
//constructor and other stuff
void virtual exec() =0; ///<= pure virtual method
};
class Movable : Entity {
void move(); //do somthing
void exec() {move();};
};
class Collidable : Entity {
void col(); //do your job
void exec(){col();};
};
std::vector<Entity*> e_v;
///push some instance
for (Entity* e : e_v)
e->exec();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With