Download Downloading - All IT eBooks
Transcript
59
Basic wandering AI
void Update() {
if (_alive) {
transform.Translate(0, 0, speed * Time.deltaTime);
...
}
}
public void SetAlive(bool alive) {
_alive = alive;
}
...
Only move if the
character is alive.
Public method allowing outside
code to affect the “alive” state
The ReactiveTarget script can now tell the WanderingAI script when the enemy is or
isn’t alive (see the following listing).
Listing 3.9
ReactiveTarget tells WanderingAI when it dies
...
public void ReactToHit() {
WanderingAI behavior = GetComponent<WanderingAI>();
if (behavior != null) {
Check if this character has a
behavior.SetAlive(false);
WanderingAI script; it might not.
}
StartCoroutine(Die());
}
...
AI code structure
The AI code in this chapter is contained within a single class so that learning and understanding it is straightforward. This code structure is perfectly fine for simple AI needs,
so don’t be afraid that you’ve done something “wrong” and that a more complex code
structure is an absolute requirement. For more complex AI needs (such as a game
with a wide variety of highly intelligent characters), a more robust code structure can
help facilitate developing the AI.
As alluded to in chapter 1’s example for composition versus inheritance, sometimes
you’ll want to split chunks of the AI into separate scripts. Doing so will enable you to
mix and match components, generating unique behavior for each character. Think
about the similarities and differences between your characters, and those differences
will guide you as you design your code architecture. For example, if your game has
some enemies that move by charging headlong at the player and some that slink
around in the shadows, you may want to make Locomotion a separate component.
Then you can create scripts for both LocomotionCharge and LocomotionSlink, and use
different Locomotion components on different enemies.
The exact AI code structure you want depends on the design of your specific game;
there’s no one “right” way to do it. Unity makes it easy to design flexible code architectures like this.
Licensed to Mark Watson <[email protected]>