Game Programming Patterns in Godot: The State Pattern (Finite State Machine)

preview_player
Показать описание


(Disclosure: As an Amazon Associate I earn from qualifying purchases.)

Learn how to implement the **State Pattern** in Godot to create a robust **Finite State Machine** for your game! In this tutorial, I’ll guide you step-by-step through building an efficient system for managing game states, perfect for character control and more.

🔔 Subscribe:

Subscribe to my channel to see more videos like this:

📖 Useful resources:

- Open source project created in this video:
- Tileset used in this project:

🔵 Follow me:

Find out about my latest videos and publications:

⏳ Timecodes:

00:00 - State Pattern introduction
01:03 - Finite State Machine implementation setup
04:06 - Defining the State class
05:52 - Defining the State Machine class
09:34 - Preparing the player scripts
12:02 - Creating the idle and movement states
15:17 - Loggign what the State Machine is doing
18:42 - Adjusting character movement
20:47 - Solving character's facing
22:08 - Adding the jump state
29:04 - Conclusion

---

Music credits:

Track: Alexi, Action, Infraction- Witch's Whispers
Music provided by Infraction No Copyright Music
Рекомендации по теме
Комментарии
Автор

Nice tutorial. I use state machine in my game, and I make my states extend Node and add them to the scene as a child node for the State Machine. Then in State Machine _ready function, I loop through the child node, assign some variables in each state, and add them to states list. This way, I can add as many states as I want without editing the code, only the scene.

mohd
Автор

Chad, was a bit to lazy to learn state lattern, but this video comes at the perfect time :D

verzocktes
Автор

An easy way to name states is to definr them in an enum and then use a variable to switch between them. So for example, enum GameState { IDLE, MOVING, ATTACKING }
Var active_state = GameState.IDLE
Etc. Then you dont need a function to return the name, and you can do things like:
Match active_state:
GameState.IDLE:
Do (x)
GameState.MOVING:
Do (y)

teagancombest
Автор

I much prefer this version than most of the other godot state patterns I've seen and tried thusfar. So much cleaner.
I have a few questions though. You have consolidated the jump and fall state quite nicely, so why not consolidate idle and move state? I'm going with "grounded" and "airborne" for now.

Also minor quirck I noticed with the last change to set the state to 'airborne' when the player is not on a floor. It does this every tic, so my warning messages went berserk telling me I was setting a new state that was the same as the current state. I didn't see those messages in your log. Any idea what I did wrong?

Kaeresh