top of page

Unreal C++ State Pattern AI Behavior

This is an implementation of the State Pattern using C++ in Unreal Engine. In this project, there are two AIs performing different behaviors according to their distance to the player. The Flee AI would wander/flee/dash, while the Chase AI would wander/chase/attack.

Specs
Date

C++

Unreal

State Pattern

02/2024

Details

This is a simple chasing and fleeing game made in Unreal Engine.


There are two enemies: a flee enemy and a chase enemy. Both the enemies will be at the wander state at the start of the game.


When the player is within a certain range to them, they turn into the flee/chase state.

  • The flee enemy will start running and flee away from the player.

  • The chase enemy will start running and chase the player.



When the player is within an even closer range to the enemies, they turn into the dash/attack state.

  • The flee enemy will dash away from the player and return to the flee state.

  • The chase enemy will jump towards the player and return to the chase state.



When the player exits the first mentioned range, they return to the wander state.


The State Pattern:

Source\AIBehavior\Public\States\BaseState.h:


I made the UBaseState class as the base state class, deriving from the UObject class.

There are three virtual functions to be overridden in the concrete state classes: Update(), OnEnter(), and OnExit().


The Update() will be called by the AAIEnemy::Tick() function every frame.

The OnEnter() will be called by the AAIEnemy::BeginPlay() after it initially assigns the UWanderState to the AAIEnemy, or the AAIEnemy::OnStateChange() function which is called by the AAIEnemy::ChangeStateTo() whenever an AAIEnemy changes to a new state.

The OnExit() will be called by the AAIEnemy::ChangeStateTo() function before it assigns the new state to the AAIEnemy.

See below: Source\AIBehavior\Private\AIEnemy.cpp:



Each state has a set of transitions, each associated with a condition and pointing to a state. In the case of my game, the wander and flee/chase states transitions based on the AI’s distance to the player, while the dash/attack states are one-time states where they immediately transition back to the flee/chase states after performing a certain action.

See below: Source\AIBehavior\Private\States\DashState.cpp:


Both the dash and attack states do not use (override) the Update() function. They rely on their OnEnter() functions (called automatically upon entering the state) to perform their action, and then transit back to the flee/chase states once the action is done.

bottom of page