Game Development Reference
In-Depth Information
'
The advantage of this method is that it
s very easy to access the component you want:
You just grab the pointer, test it, and go. The disadvantage is that you can begin to
couple multiple components tightly together. After a while, you
ll realize that every
actor needs to have a position somewhere because every other component asks for
it. As long as you make sure to always gracefully handle the case where no compo-
nent exists, this scenario shouldn
'
'
t be too bad.
Events
If you really want to decouple your components, another method is to use an event
system. The actor acts as a messaging service that its components (and other sys-
tems) can use to post messages about important events. Each component registers
which events it cares about, and when the actor receives a message, it distributes it
to the appropriate components.
For example, let
s say the AI component wants to move the actor. It just posts a mes-
sage requesting the move to a new position, and the actor tells the appropriate com-
ponents. The AI component doesn
'
'
t have to know, nor does it care, which
components receive the message.
This situation certainly keeps components from being decoupled from one another,
but it also raises a few concerns. Sometimes it
s important to know which component
is answering the message and in which order. Say you post a move message, and the
renderable component receives it first. It updates its internal positions, and everything
is fine. Then the physics component receives the new position and detects it as being
invalid. Now what? The physics system could send an event to disregard the old posi-
tion and give the new position, but this could cause an oscillation where the AI com-
ponent and physics component are battling each other trying to move the actor. The
actor will mostly appear to vibrate, jumping back and forth between two positions.
There are certainly ways around this issue. You could (and probably should) have all
message registration defined in data, which allows a great deal of control on a per-
actor basis.
Game events are covered in detail in Chapter 11.
'
The Best of Both Worlds
The best solution to these problems is to use a mixture of the two communication
methods. Events are great for broadcasting things that other components may or
may not care about, and direct access is great when you need to directly tell some-
thing to a specific component. Why not use both? Many games do.
 
 
 
Search WWH ::




Custom Search