Skip to main content
edited title
Link
vargonian
  • 829
  • 1
  • 9
  • 12

Where to update Game Entity Drawables How should I isolate game entities with their concrete Drawable components (in C#) ?

edited tags
Link
vargonian
  • 829
  • 1
  • 9
  • 12
Source Link
vargonian
  • 829
  • 1
  • 9
  • 12

Where to update Game Entity Drawables (in C#) ?

I've designed my game entities using a common pattern of separating the entity from its components. In my case, I've used the Strategy pattern to give each of my entities an IDrawable component.

I construct my entities using a factory, which constructs the entity and adds an appropriate drawable, e.g.:

public static PlayerEntity CreatePlayerEntity(...)
{
   PlayerEntity playerEntity = new PlayerEntity(...);
   SpriteDrawable spriteDrawable = new SpriteDrawable(...);
   playerEntity.Drawable = spriteDrawable;

   ...

   return playerEntity;
}

Now here's the question: If I later want to update the player drawable in some way (e.g. modify the sprite, change the animation, etc.), how and where should I do this?

My first thought is to have C# events that the PlayerEntity publishes and the Drawable subscribes to, but this gets tricky from a purist standpoint, because it's hard to do this without the Drawable requiring a reference to a PlayerEntity. My current hacky solution is to subscribe to these events from within the CreatePlayerEntity() method itself, using anonymous delegates, which can take advantage of the fact that you've still got a reference to the concrete IDrawable implementation. It just doesn't seem right for the factory to have this responsibility, though:

public static PlayerEntity CreatePlayerEntity(...)
{
   PlayerEntity playerEntity = new PlayerEntity(...);
   SpriteDrawable spriteDrawable = new SpriteDrawable(...);
   playerEntity.Drawable = spriteDrawable;

  playerEntity.SomeEvent += new EventHandler((sender, e) => { spriteDrawable.Texture = blah; });

   ...

   return playerEntity;
}

What is a better, approved way to accomplish this communication between concrete implementations?