1
\$\begingroup\$

I'm currently working on a 2d physics based plat former, kinda in the style of super meat boy. In super meat boy, you have multiple levels and I want a similar sort of thing but is there a general way of handling creating entities at the start of a level. Since I'm using an entity-component design and using tiled editor to load levels (and even lua script do to some more config/level related logic), how would I handle creating entities?

Currently, I parse my tiled xml map and do something like

if("MovingPlatform"){
   createMovingPlatform(mapObject)
}elseif("SomeOtherEntity"){

} //... so on so forth

But this will soon become a really long branch of if statements just to load my entities. Is there a cleaner design pattern or way of doing this. I was thinking to use a map or strings to classes that create that entity like so:

 //in constructor of level loader
 entityCreatorMap["MovingPlatform"] = MovingPlatformEntityLoader()

//somewhere later creating my entities by parsing xml
entityCreatorMap[mapObject.getName()].create(mapObject)

But that will be lots of lines initialising these kind of objects. Any ideas?

\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

You can make a singleton which will store relationships between name and loader instance and register loaders to it in loader's constructor. You'll have same operations like in your example, but it would be distributed. Here is an example:

MovingPlatformEntityLoader::MovingPlatformEntityLoader()
{
    EntityLoaderRegistry::registerEntity( "MovingPlatform", this );
}

static MovingPlatformEntityLoader loader;

When MovingPlatformEntityLoader's constructor will be called loader would be registered in registry and other classes could use it. To call constructor you can create instance of MovingPlatformEntityLoader just in this .cpp file with static modifier like in the example.

Pluses of this technique:

  • You don't need hard-modifiable registration method.
  • You can add new loaders even if you have no access to all code of a game (useful for plugins).

Minuses:

  • If you have multiple modules and use dynamic linkage (for examples for plugins) you will have problems with linkage's "bad habbit" to forget unused .cpp files (you must link this files manually to dll's entry point).
  • You can't predict order of creating loaders. That's why singleton should be accessed by a static method like in the example.
\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .