In this lesson, you will learn how to structure an AI’s behavioral flow using a finite state machine (FSM) that reacts dynamically to data from your AI Perception system.
Understanding State-Driven Logic
While your AI Perception system (Lesson 23) handles raw data—like seeing a player or hearing a noise—a State-Driven Decision Model acts as the "brain" that translates that data into meaningful behavior. An FSM keeps your AI in one specific state at a time, preventing conflicting behaviors (like trying to run away and attack simultaneously) by strictly defining the rules for when a transition can occur.
The Three-State Architecture
For our intermediate-level implementation, we will use three primary states: Idle, Alert, and Combat.
- Idle: The default state; the AI wanders or patrols.
- Alert: Triggered when a sound is heard or a target is briefly sighted; the AI stops and investigates.
- Combat: Triggered when the target is fully perceived; the AI chases and attacks.
Implementing the State Logic
In your AIController, you should maintain an EAIState enumeration. Using a Switch statement inside your Tick or a dedicated "Decision" function allows you to decouple your logic.
void AMyAIController::UpdateAIState(EAIState NewState)
{
CurrentState = NewState;
switch (CurrentState)
{
case EAIState::Idle:
// Stop movement, play idle anims
break;
case EAIState::Alert:
// Move to last known location, increase perception radius
break;
case EAIState::Combat:
// Chase target, trigger combat montages
break;
}
}
The key is to hook your OnPerceptionUpdated delegate to trigger these transitions. For example, if SensedTarget is valid, transition to Combat. If the timer for a lost target expires, transition from Combat back to Alert. This keeps your AI predictable and easy to debug, as you can always print the current state to the screen to see exactly what "mood" your AI is in.
Key Takeaway: A state-driven model uses your perception data as a filter to trigger transitions, ensuring your AI only executes the specific logic appropriate for its current level of awareness.