views:

104

answers:

4

For a 2D game I'm making (for Android) I'm using a component-based system where a GameObject holds several GameComponent objects. GameComponents can be things such as input components, rendering components, bullet emitting components, and so on. Currently, GameComponents have a reference to the object that owns them and can modify it, but the GameObject itself just has a list of components and it doesn't care what the components are as long as they can be updated when the object is updated.

Sometimes a component has some information which the GameObject needs to know. For example, for collision detection a GameObject registers itself with the collision detection subsystem to be notified when it collides with another object. The collision detection subsystem needs to know the object's bounding box. I store x and y in the object directly (because it is used by several components), but width and height are only known to the rendering component which holds the object's bitmap. I would like to have a method getBoundingBox or getWidth in the GameObject that gets that information. Or in general, I want to send some information from a component to the object. However, in my current design the GameObject doesn't know what specific components it has in the list.

I can think of several ways to solve this problem:

  1. Instead of having a completely generic list of components, I can let the GameObject have specific field for some of the important components. For example, it can have a member variable called renderingComponent; whenever I need to get the width of the object I just use renderingComponent.getWidth(). This solution still allows for generic list of components but it treats some of them differently, and I'm afraid I'll end up having several exceptional fields as more components need to be queried. Some objects don't even have rendering components.

  2. Have the required information as members of the GameObject but allow the components to update it. So an object has a width and a height which are 0 or -1 by default, but a rendering component can set them to the correct values in its update loop. This feels like a hack and I might end up pushing many things to the GameObject class for convenience even if not all objects need them.

  3. Have components implement an interface that indicates what type of information they can be queried for. For example, a rendering component would implement the HasSize interface which includes methods such as getWidth and getHeight. When the GameObject needs the width, it loops over its components checking if they implement the HasSize interface (using the instanceof keyword in Java, or is in C#). This seems like a more generic solution, one disadvantage is that searching for the component might take some time (but then, most objects have 3 or 4 components only).

This question isn't about a specific problem. It comes up often in my design and I was wondering what's the best way to handle it. Performance is somewhat important since this is a game, but the number of components per object is generally small (the maximum is 8).

The short version

In a component based system for a game, what is the best way to pass information from the components to the object while keeping the design generic?

+2  A: 

Use an "event bus". (note that you probably can't use the code as is but it should give you the basic idea).

Basically, create a central resource where every object can register itself as a listener and say "If X happens, I want to know". When something happens in the game, the responsible object can simply send an event X to the event bus and all interesting parties will notice.

[EDIT] For a more detailed discussion, see message passing (thanks to snk_kid for pointing this out).

Aaron Digulla
Sounds like message-passing architecture, as it's typically called.
snk_kid
This is probably the most generic approach. A bit over the top for a small game like mine, but worth considering as a general solution.
Firas Assaad
Well, it does make the design pretty simple since it's so generic and easy to implement (just < 50 lines of code in Java, 20 in Python). When your game works, you can still optimize some bits but it gets you up and running quickly.
Aaron Digulla
+1  A: 

One approach is to initialize a container of components. Each component can provide a service and may also require services from other components. Depending on your programming language and environment you have to come up with a method for providing this information.

In its simplest form you have one-to-one connections between components, but you will also need one-to-many connections. E.g. the CollectionDetector will have a list of components implementing IBoundingBox.

During initialization the container will wire up connections between components, and during run-time there will be no additional cost.

This is close to you solution 3), expect the connections between components are wired only once and are not checked at every iteration of the game loop.

The Managed Extensibility Framework for .NET is a nice solution to this problem. I realize that you intend to develop on Android, but you may still get some inspiration from this framework.

Martin Liversage
This is a good idea. It is a very generic approach and wiring connections between on components on initialization makes it efficient. It does seem a bit too involved for a small game, but I would consider it if my design gets too complex or for bigger projects. Thanks.
Firas Assaad
+5  A: 

We get variations on this question three or four times a week on GameDev.net (where the gameobject is typically called an 'entity') and so far there's no consensus on the best approach. Several different approaches have been shown to be workable however so I wouldn't worry about it too much.

However, usually the problems regard communicating between components. Rarely do people worry about getting information from a component to the entity - if an entity knows what information it needs, then presumably it knows exactly what type of component it needs to access and which property or method it needs to call on that component to get the data. if you need to be reactive rather than active, then register callbacks or have an observer pattern set up with the components to let the entity know when something in the component has changed, and read the value at that point.

Completely generic components are largely useless: they need to provide some sort of known interface otherwise there's little point them existing. Otherwise you may as well just have a large associative array of untyped values and be done with it. In Java, Python, C#, and other slightly-higher-level languages than C++ you can use reflection to give you a more generic way of using specific subclasses without having to encode type and interface information into the components themselves.

As for communication:

Some people are making assumptions that an entity will always contain a known set of component types (where each instance is one of several possible subclasses) and therefore can just grab a direct reference to the other component and read/write via its public interface.

Some people are using publish/subscribe, signals/slots, etc., to create arbitrary connections between components. This seems a bit more flexible but ultimately you still need something with knowledge of these implicit dependencies. (And if this is known at compile time, why not just use the previous approach?)

Or, you can put all shared data in the entity itself and use that as a shared communication area (tenuously related to the blackboard system in AI) that each of the components can read and write to. This usually requires some robustness in the face of certain properties not existing when you expected them to. It also doesn't lend itself to parallelism, although I doubt that's a massive concern on a small embedded system...?

Finally, some people have systems where the entity doesn't exist at all. The components live within their subsystems and the only notion of an entity is an ID value in certain components - if a Rendering component (within the Rendering system) and a Player component (within the Players system) have the same ID, then you can assume the former handles the drawing of the latter. But there isn't any single object that aggregates either of those components.

Kylotan
I kind of expected this to be the answer; that there are many approaches and they are all workable in different contexts. You are right about completely generic systems, I was over-engineering and worrying about problems that don't exist.
Firas Assaad
+5  A: 

Like others have said, there's no always right answer here. Different games will lend themselves towards different solutions. If you're building a big complex game with lots of different kinds of entities, a more decoupled generic architecture with some kind of abstract messaging between components may be worth the effort for the maintainability you get. For a simpler game with similar entities, it may make the most sense to just push all of that state up into GameObject.

For your specific scenario where you need to store the bounding box somewhere and only the collision component cares about it, I would:

  1. Store it in the collision component itself.
  2. Make the collision detection code work with the components directly.

So, instead of having the collision engine iterate through a collection of GameObjects to resolve the interaction, have it iterate directly through a collection of CollisionComponents. Once a collision has occurred, it will be up to the component to push that up to its parent GameObject.

This gives you a couple of benefits:

  1. Leaves collision-specific state out of GameObject.
  2. Spares you from iterating over GameObjects that don't have collision components. (If you have a lot of non-interactive objects like visual effects and decoration, this can save a decent number of cycles.)
  3. Spares you from burning cycles walking between the object and its component. If you iterate through the objects then do getCollisionComponent() on each one, that pointer-following can cause a cache miss. Doing that for every frame for every object can burn a lot of CPU.

If you're interested I have more on this pattern here, although it looks like you already understand most of what's in that chapter.

munificent
I really like this idea and I'm going to use it for this particular scenario. I'm familiar with your book/site and in fact my implementation is based on that chapter (that's why I'm calling it GameObject and not Entity for example). I know you talk about component communication in there but I was wondering how generic should the entity be when communicating with its components. Thanks for the wonderful resource (it's about time you added another chapter!).
Firas Assaad
Yeah, I know! The book is unfortunately on hiatus for a while. I recently left the game industry and moved across the country, so I've got other stuff on my mind. Hopefully, I'll get back to it soon.
munificent
I've been mulling over the entity/component framework for a couple of years now, occasionally going back to try it again with a different project when I get the free time. If only I had have read that chapter back then rather than the more technical descriptions, I may have been significantly better off :). Excellent read. It seems like your answer is correct: push up really common stuff (e.g. position), couple components that are behaviourally coupled already (e.g. physics and collision), and fire some messages for simple cross-component triggers. Now I'm pumped to give it another shot!
Pie21