Game Development Reference
In-Depth Information
Perform the following steps to implement the
npcScript
class:
1. A private variable of the type
npcState
, named
state
, will track the value
of this enum for each NPC instance:
private npcState state;
2. In order for our NPC to be able to follow a parametric curve when patrolling,
we give the
npcScript
class a
SplineMgr
class to interpolate a user-
defined path. A public
showPath
Boolean is also provided for debugging:
public bool showPath;
public SplineMgr path;
3. An instance of a data-driven system for detecting scenarios and dispatching
responses at runtime is also added to the
npcScript
class. This class will
act as the brain of the NPC, deciding when to change states based on the
state of the game world:
public npcDecisionMgr decisionMgr;
4. Each time an in-game NPC is activated, the
start()
script will first compute
the debug path visualization for the spline and then set the NPC into the
patrol
mode so that it will start walking. The
computeDebugPath
method
will walk through the spline from the start to the end and store a series of line
segments that the debug line renderer can use to draw the spline when we
need to visualize it. The second line of code sets the NPC into the
patrol
state, which tells the NPC to follow the spline path. We will discuss splines
later in this chapter:
path.computeDebugPath();
SetState(npcState.patrol);
5. The
npcScript
class implements a
SetState(newstate s)
method to
allow the client code to change the state of the NPC. A
switch
statement
implementation provides a means of specializing one-off code that executes
once when the state actually switches. This is how we implement the
OnEnter
event for each state in the enumeration.