Graphics Reference
In-Depth Information
There will be times when we may need to force the state of the bot from another script,
such as telling it which state to start in when the game begins. Use the function SetAIState
for that, passing in an AIState.
public virtual void SetAIState( AIState newState )
{
// update AI state
currentAIState= newState;
}
If chasing is required, the SetChaseTarget() function should be used to pass in a refer-
ence to the transform that needs chasing. It gets stored into a variable named followTarget.
public virtual void SetChaseTarget( Transform theTransform )
{
// set a target for this AI to chase, if required
followTarget= theTransform;
}
The Update() function is called by Unity at each frame update, but we need to be sure
that the script has properly initialized before doing anything significant with it because it
may be possible for Update to be called before Init() has finished its run.
public virtual void Update ()
{
// make sure we have initialized before doing anything
if( !didInit )
Init ();
If AIControlled is not set to true, the function drops out before it has a chance to call
for an update to the AI—with the Boolean variable AIControlled, it makes it possible to
turn on or off the AI control at will. This functionality is useful in situations where we
might want AI code to take control of a player but not at the start of the game; for example,
AI might take over at the end of a racing game when a race is complete, and we want the
player's car to continue driving without any player input.
// check to see if we're supposed to be controlling the player
if( !AIControlled )
return;
// do AI updates
UpdateAI();
}
UpdateAI() is right at the core of the script—it is called by the Update() function
shown earlier and deals with coordinating the bot to do what it should:
public virtual void UpdateAI()
{
In some cases, the AI script does not manipulate its object directly but rather acts as
an input provider. The reason it works this way is so that AI can use the same movement
controllers as the player without having to recode movement each time. For example, in
the example game Metal Vehicle Doom in Chapter 11, the AI cars use the same car physics
Search WWH ::




Custom Search