Finite State Machines — Giving AI Choices

The AI “Chose” to stop at this pillar, as it determined it was a safe location from the player.

In the realm of AI development, the term “Finite State Machine” is thrown around quite frequently. In short, FSMs are the logical composition that gives an AI the ability to “choose” based on a set of predetermined instructions. These instructions take into consideration a plethora of variables dependent on the type of game and the purpose of the AI itself.

Simple Illustration.

FSMs can also be considered glorified switch statements. In essence, swapping the AIState is like changing cases in a switch. The AIStates are listed in an Enumeration — A collection of constants. As the AI is always doing something, these different logic paths are best held as Enumerations.

Now that the three possible states are defined, I utilized a switch statement to handle when the AI should change states.

_IAmHiding is a boolean used to stop an infinite loop issue.

So now that the basic rules have been established, let’s look at how the targets “think” when they first spawn in.

The AIState can be seen in the Inspector, so we know exactly what each target is logically “thinking”.

When a target spawns in, it calculates a safe zone that it wants to reach, while also keeping the location of the finish line in mind so that it always moves towards its ultimate goal.

The finish line is the final waypoint.

Now that it has calculated its path, it will navigate towards the projected waypoint at a random speed (some targets are faster than others).

You can clearly see one target overtake another due to the speed variance.

Once the target arrives at the waypoint, it swaps to the AIState.Hide, and waits for a random time. During this pause (where the target is obstructed for the player and thus not in danger) the AI calculates the next waypoint it should attempt to reach.

The AI pauses while it “thinks”.

The final AIState is AIState.Death. This state will simply hold the OnDeath event data (incrementing score, playing animation, etc). We could easily add an attack state or a sprint state by expanding the Enumeration and switch statement with the appropriate states.

Hopefully this sheds some light onto simple AIStates and how they can be incorporated into your future projects!

Next time, I will cover how to shoot these targets from the player’s sniper nest, as well as triggering the OnDeath logic!



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Jack Leavey

Jack Leavey


I am a software engineer with years of experience branching into game development, specifically in Unity. Follow along for guides on creating game mechanics!