Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 1

Finite State Machine Fundamentals

Recommended resources

Hello! Welcome to your first lesson on Finite State Machines (FSMs) for game development.

Your goal is to master FSMs to build more robust and manageable systems for NPC AI, UI flows, and game state in Roblox. Based on your preference, we'll start with the fundamental theory before diving into practical Luau implementation.

This lesson tackles the very first learning outcome: Define what a state, transition, and event are in the context of a finite state machine. By the end, you'll have a clear mental model of these three core building blocks, setting a strong foundation for the entire course.

1. The "Why": What Problem Do FSMs Solve?

As an experienced programmer, you've likely encountered situations where you need to manage an object that can behave in many different ways. A common approach is to use a series of if/elseif/else statements and boolean flags to check what the object should be doing.

For a simple object, this works fine. But what happens when you have an NPC with states like Idle, Patrolling, Chasing, Attacking, and Fleeing? The logic can quickly become a complex web of nested conditionals that is difficult to read, debug, and extend. This is often called "spaghetti code."

Finite State Machines offer a powerful design pattern to solve exactly this problem. They provide a structured way to model an object's behavior, making your code cleaner, more organized, and easier to maintain.

To see a practical example of this problem in a game development context, let's watch a short segment from the following video.

An introduction to finite state machines and the state pattern for game development

This video from The Shaggy Dev, titled 'An introduction to finite state machines...', clearly illustrates how character controller logic can become unmanageable and sets the stage for why FSMs are so useful.

Watch from the beginning until the 4:07 mark. Pay close attention to the example of a platformer character and how adding new abilities (jump, fall, attack) makes the conditional logic increasingly complex. The flowchart at 02:35 is a key moment where the logic is untangled into a visual FSM.

As the video demonstrates, by thinking in terms of distinct "states" and the rules for moving between them, we can organize our logic much more effectively than with a long chain of if statements.


2. The "What": Defining the Core Concepts

Now that we understand the problem FSMs solve, let's formally define their core components. We'll use a simple, non-technical analogy of an oven to make these ideas concrete.

Understanding State Machines, Part 1: What Are They?

This video from the MATLAB channel provides excellent, concise definitions for the fundamental parts of an FSM. It uses a simple oven analogy to explain the concepts without getting into code.

Please watch from 0:06 to 01:59, and then the summary from 02:52 to 03:04. Focus on how the video defines states, transitions, and events using the oven example.

Based on the video, here are the formal definitions:

  • State: A state is a specific mode or condition that a system can be in at any given time. The key rule is that an FSM can only be in one state at a time.

    • Analogy: The oven can be Off, Heating, or Idling. It cannot be Off and Heating simultaneously.
  • Transition: A transition is the change from one state to another. It's a one-way path.

    • Analogy: The arrow going from the Off state to the Heating state.
  • Event (or Input): An event is the trigger that causes a transition to occur. It's the condition that must be met for the FSM to move to a new state.

    • Analogy: Pressing the "bake" button is the event that triggers the transition from Off to Heating. The oven temperature becoming "too hot" is the event that triggers the transition from Heating to Idling.

3. FSMs in a Game Development Context

These concepts map directly to game development. The excellent book Game Programming Patterns by Robert Nystrom provides a very clear summary. Let's read a short excerpt that defines these terms from a programmer's point of view.

State · Design Patterns Revisited

This chapter from 'Game Programming Patterns' grounds the theory in a character controller example, similar to the first video we watched. It provides a crisp, bulleted list defining the core components of an FSM.

Please read the section titled 'Finite State Machines to the Rescue'. Focus on the four bullet points that start with 'You have a fixed set of states...'. This is a perfect summary of the concepts we've just discussed.

To summarize the key points from that reading:

  • States are the distinct things your character or object can be doing (e.g., Standing, Jumping, Ducking).
  • The object can only be in one state at a time (you can't be Jumping and Ducking at once).
  • Events are the inputs that the machine receives (e.g., button presses like B button pressed, or game conditions like player health < 10%).
  • Transitions define how to move from the current state to a new state when a specific event occurs (e.g., in the Standing state, the down button press event transitions you to the Ducking state).

4. Putting It All Together: A Visual Example

A common way to design and understand an FSM is to draw a state diagram. This is exactly like the flowcharts you saw in the videos. The states are boxes or circles, and the transitions are arrows connecting them, labeled with the events that trigger them.

Let's look at a state diagram for an NPC in a game, which is one of your key goals.

Game Character Behavior FSM
This diagram shows a simple FSM for an NPC. The rounded rectangles are the **states**: `Farming`, `Storing`, `Sleeping`, and `Eating`. The arrows are the **transitions**. The labels on the arrows, such as `Inventory Full`, `Hunger High`, and `Tired`, are the **events** that trigger those transitions.

Let's trace the logic:

  1. The NPC starts in the Farming state.
  2. If the Inventory Full event occurs, it transitions to the Storing state.
  3. After storing its items, it automatically transitions back to Farming.
  4. However, if at any point the Hunger High event happens, the NPC will immediately transition to the Eating state, no matter what it was doing. This shows how FSMs help prioritize behaviors.

This simple diagram clearly and unambiguously defines the NPC's behavior. Imagine trying to write this with only if statements—it would be much harder to follow.


Conclusion

In this lesson, we established the core vocabulary of Finite State Machines. You now have a solid theoretical understanding of the "what" and "why."

Here are the key takeaways:

  • State: A distinct status or behavior of your system (e.g., Idle, Chasing). An FSM is always in exactly one state.
  • Event: An input or trigger that can cause a change of state (e.g., PlayerSpotted, HealthLow, TimerExpired).
  • Transition: The rule that defines the shift from a source state to a destination state when a specific event occurs.

In the next lesson, we'll move from defining these concepts to applying them. You will get to draw a state diagram for a simple real-world scenario, taking your first step toward designing your own FSMs.