Decision making for AI can be handled in many different ways, and one common way is to use a Finite State Machine (FSM). An FSM contains a number of predefined states. Each state has a set of functionality and behavior tied to it. Each state also has a number of conditions for when it can change to another state.
In this recipe, we'll define a state machine that will emulate a common AI behavior in games. In fact, it will be more advanced than many games, which usually have AI that can only either move around on a path, or attack. Our AI will have three states, Patrol, Attack, and Retreat, as shown in the following diagram:.
PatrolState will be the default and fallback state. It will perform ...