Game Development Reference
In-Depth Information
end
end
There are a number of issues with this implementation. First and foremost, as the
complexity of our state machine increases, the readability of the Update and
SetState functions decrease. If we had 20 states instead of the three in this ex-
ample, the functions would end up looking like spaghetti code.
A second major problem is the lack of flexibility. Suppose we have two different
AIs that have largely different state machines. This means that we would need to
have a different enum and controller class for each of the different AIs. Now, sup-
pose it turns outthat bothofthese AIsdoshare a couple ofstates incommon, most
notably the Patrol state. With the basic state machine implementation, there isn't a
great way to share the Patrol state code between both AI controllers.
OnecouldsimplycopythePatrolcodeintobothclasses,buthavingnearlyidentic-
al code in two separate locations is never a good practice. Another option might be
to make a base class that each AI inherits from and then “bubble up” the majority
of the Patrol behavior to this base class. But this, too, has drawbacks: It means that
any subsequent AI that needs a Patrol behavior also must inherit from this shared
class.
So even though this basic implementation is functional, it is not recommended for
more than the simplest of AI state machines.
State Design Pattern
A design pattern is a generalized solution to a commonly occurring problem. The
seminal topic on design patterns is the so-called “Gang of Four” Design Patterns
topic, which is referenced at the end of this chapter. One of the design patterns is
the State pattern, which allows “an object to alter its behavior when its internal
state changes.”
This can be implemented using class composition. So the AIController “has-
a” AIState asamembervariable.Eachspecificstatethensubclasses AIState .
Figure 9.11 shows a rough class diagram.
Search WWH ::




Custom Search