# Finite State Machines for Enemies (AI vs. Entity States)

Finite State Machines are a great tool for simplifying a system where an Entity has many states it can be in with different conditions that determine what state to transition to. This works well for representing a Player in a platformer, because the state machine can keep track of what state the Player is in based off of user input. This state machine would largely be based around animation states (running, jumping, attacking, etc...)

However, although this makes sense for handling Entity states and keeping track of animations, what about AI states? FSMs also provide a great framework for handling how enemies behave when interacting with the Player. My question is, what is the relationship between this FSM and the FSM that handles general entity states?

For example, in general, an enemy can be running, attacking, idling, jumping, falling, crouching, etc... In terms of AI, the enemy could be following, attacking, running away, patrolling, etc... As you can see, these states are mostly different with some overlap. I want to know how to handle these two different FSMs in code.

Questions:

1. Should I keep these FSMs separate and update the states separately or should I somehow combine them into one FSM?
2. If I keep the FSMs separate, how can I can I handle interdependence (behavior in the AI might change if suddenly the Enemy walked off a cliff and is now falling)?
• For my turn based game I went with a conditional weighted decision system. I figure out what the enemy can do, and then decide which one is more important based upon the value of that action. – Krythic Dec 16 '16 at 3:48

## 1 Answer

1. I think that you should keep each individual "state" separate. For instance, if you have an enemy that will chase after the player if it sees the player, it will start following and running. If you had an enemy that only tails the player, it will start following, but not running. The code might look like this in pseudocode:

class enemy{
private:
bool running;
bool pursuing;
running = false;
pursuing = false;

public:
class chaser{
void detectPlayer(){
if (enemy can see player) then {
pursuing = true;
running = true;
}
}

class tail{
void detectPlayer(){
if (enemy can see player) then {
pursuing = true;
}
}
}
}

2. You would have to code the interdependencies into various functions. You can either do an event based function that updates all the relevant states whenever an enemy falls off of a cliff (which is what I have above) or you can have it be part of his general update method that updates all his states.