Game Development Reference
In-Depth Information
6. When entering the
patrol
state, we set the head of the
SplineMgr
class to
the NPC GameObject. This permits the
SplineMgr
class to attach the NPC
to the curve and update its position each frame. We also set the playback
mode on the
SplineMgr
class to loop so that when the NPC reaches the
end of the curve, it will loop back to the start; other modes exhibit different
playback behavior along the curve:
path.HeadObj = this.gameObject;
path.SetPlaybackMode(splineMgr.ePlaybackMode.loop);
7. When entering the
turnToPlayer
state, we set the playback mode of the
SplineMgr
class to none. This has the effect of stopping the velocity of the
NPC model:
path.SetPlaybackMode
(SplineMgr.ePlaybackMode.none);
8. The
npcScript
class implements an
Update()
method, (which all classes
that inherit from
MonoBehavior
need to implement), which has four logical
segments that are computed for each frame.
9. First, the distance from the player and the NPC is calculated. This quantity is
stored for later processing:
if (player)
{
Vector3 v = h.transform.position -
this.transform.position;
distanceToHero = v.magnitude;
}
10. A
switch
statement permits specialization of the code that the NPC needs
to perform for each frame. In the
patrol
state, the NPC looks at the point
in front of itself; this is a quantity that the
SplineMgr
class conveniently re-
turns for us by evaluating the spline at a point slightly further ahead on the
curve than the
HeadObj
itself:
this.transform.LookAt(path.TargetObj.transform.position);
11. While in the
turnToPlayer
state, the NPC looks at the player position: