Game Development Reference
In-Depth Information
This class is a bit of a spoiler. I wrote the AI system for the Teapot Wars sample
game you ' ll see in Chapter 21, A Game of Teapot Wars, while writing this chapter,
so it made sense to use it here as an example of a working state machine. The ene-
mies are all teapots, hence the reference to teapots in the code.
Every teapot is given a state machine instance, which contains a back-reference to the
teapot itself (the Lua script component), a current state, and a brain. The current
state is the state the teapot is in right now. The brain is an object containing a
Think() function that returns the best state for the teapot.
The Destroy() function is self explanatory. The SetState() function checks to
see if the current state is nil or if the new state is not the same as the current
state. If either condition is true, it sets the new state. We need to check to make
sure the states are different because choosing the same state really means choosing
to continue doing what the teapot is doing.
ChooseBestState() tells the state machine to find the best state for the given sit-
uation. This is the AI update function and is called periodically by a script process. If
the teapot has a brain, it calls the Think() function on that brain to find the best
state and attempts to set it. The Update() function runs the current state and is
called every frame by another script process. The _ InternalSetState() function
instantiates the state object and calls its Init() function.
States are typically self contained with rules defining how the state machine transi-
tions from one state to another. One of the big advantages of state machines is that
states can often be reused among many different creatures. The chances are good that
you
ll get a lot of use out of a patrol or attack state, and with a bit of parameteriza-
tion you can reuse these states across many different types of creatures.
Let
'
s say we want to make a guard that patrols an area until the player gets within a
certain radius and then attacks. If the player gets too far away, he resumes his patrol.
If his health gets too low during the fight, he runs away. To do this with a state
machine, you need three states: one that defines the pacing behavior, one for the
attack behavior, and the third for the running away behavior. These states are con-
nected by transitional logic, as shown in Figure 18.1.
'
Figure 18.1
Guard
'
s state machine.
Search WWH ::




Custom Search