How do you keep your character from jumping while they're already in mid-air? How do you make sure they only play the "Run" animation while moving? You use a Finite State Machine (FSM).
The Core Concept
An FSM is a system that can only be in one state at a time. It defines: 1. States: (Idle, Running, Jumping, Attacking). 2. Transitions: Rules for moving between states.
This prevents "spaghetti code" where you have dozens of messy if/else statements conflicting with each other.
const states = {
IDLE: 'idle',
RUN: 'run',
JUMP: 'jump'
};
function transition(newState) {
if (currentState === states.JUMP && newState === states.RUN) {
return; // Illegal: Can't transition to run while in air!
}
currentState = newState;
}
Why It Matters
FSMs make your code predictable. By mapping out exactly how an entity can move from one behavior to another, you eliminate bugs like "moon-walking" or "double-jumping" by accident. It's the secret to making a game feel polished and intentional.
The Takeaway
If you find yourself writing too many nested if statements for your AI or player, it's time to build a State Machine.