Game Development Reference
In-Depth Information
Note
All .NET objects implement the GetType method, which returns a Type object. The Type object
has a Name method that we will use to get the short name of a type. The class name Type is
necessarily confusing; it is hard to clearly name an object that holds the type information of other
objects. Besides being a method of every object, GetType can be called with a class name as a
parameter to get a Type object for the class without having to create an object of that class. We
will use that capability later to get the name of a state's type without having to create a State
object.
This code takes a State object and gets the name of the type of the object. The
state was passed in as an object of type BasicState . So why won't all objects have
the same stateName , BasicState ? The GetType method of an object ignores
the type of the variable and instead uses the type of the underlying object. In any
case, the object passed in can never have been created as type BasicState because
we marked BasicState as MustInherit . Put another way, there are no generic
mammals, even though dogs and cats are mammals. The object passed in will
have been created with a type of FleeState , HidingState ,or AttackState , all of
which we will create very soon.
Our design called for the first state to be loaded to be the Start state. So we
checked the count of items in the States collection to see if there were any states
already loaded. If the count is zero, we are loading the first state, so we make it the
current state.
Our states are different from each other—one of the hallmarks of a good FSM
implementation. Before we add a state to the States collection, we check to make
sure it is not already there. If not, we add the state to the collection, keyed by the
stateName . If we add an object to a collection and also specify a key string, we can
later access the object using that key. Keys must be unique in a collection. What
the code actually does is check to see if the key is present in the collection; it does
not check the actual objects. Keys are hashed, which means that finding an object
in a collection of many objects happens reasonably quickly.
The FSM needs one more member: a way to make the machine run. Add the
following code to the class:
Public Sub RunAI(ByVal World As Monster)
If States.Contains(currentStateName) Then
'Get the object using the name
Dim stateObj As BasicState
stateObj = States(currentStateName)
 
 
Search Nedrilad ::




Custom Search