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

In this video, we'll discuss finite state machines and how they can be used to write cleaner, more maintainable, and more expandable code for your games. We'll look at the naive way of managing state in a game, how we can improve upon that method slightly with enumerators, and finally how to build a robust system using the state pattern.
Intro: 00:00
Life without state machines: 00:54
Finite state machines: 02:38
Using enumerators: 04:55
The state pattern: 06:09
Final thoughts and where to go next: 10:28
Game Programming Patterns: gameprogrammingpatterns.com/s...
Video transcript: shaggydev.com/2021/11/01/stat...
Artwork by Kenney: www.kenney.nl/

Пікірлер: 77

  • @vrakitine
    @vrakitine2 күн бұрын

    When I was earning my master's degree, I heard a lot about finite state machines (FSMs), but it was all theory - like clouds in the sky: there's a lot of water, but you can't drink it. I toiled for three months after graduating until I implemented my first FSM in code in 1981. Now, there is a programming methodology based on this concept - v-agent oriented programming (VAOP) - with many examples of its implementation. It's best to start learning about VAOP with this article on Medium: "Bagels and Muffins of Programming or How Easy It Is to Convert a Bagel into a Black Hole". With VAOP, you can implement FSM in any programming language.

  • @mrgatopascuero9973
    @mrgatopascuero997327 күн бұрын

    My brain just melted and it's a good sign that there's a lot I still have to learn and experiment with.

  • @pedroparamo5
    @pedroparamo52 жыл бұрын

    What a fantastic lecture. There isn’t a single second wasted in it. Instant sub, I hope your channel keeps growing!

  • @TheShaggyDev

    @TheShaggyDev

    2 жыл бұрын

    Thank you! Glad you liked it!

  • @osayami
    @osayami2 жыл бұрын

    Man this is the type of high quality content that Godot is missing! Thanks for the great video and keep up the amazing work. Subscribed

  • @TheShaggyDev

    @TheShaggyDev

    2 жыл бұрын

    Thank you! And welcome aboard!

  • @bisquestudio
    @bisquestudio2 жыл бұрын

    this is what I'm looking for, you are so detailed in explaining the steps,thank you for it ,

  • @TheShaggyDev

    @TheShaggyDev

    2 жыл бұрын

    Glad you found it useful! Thanks for watching!

  • @Pixelaze
    @Pixelaze2 жыл бұрын

    State Machines changed my life.

  • @TheShaggyDev

    @TheShaggyDev

    2 жыл бұрын

    It really does make a huge difference in your code organization once you get comfortable with them. Probably one of the most common patterns I use.

  • @felipeminuzzo6410
    @felipeminuzzo6410 Жыл бұрын

    I implemented this kind of state machine in my current game after watching your videos and I very happy with the result! It made the states easier to code, debug and control

  • @aventurileluipetre
    @aventurileluipetre2 ай бұрын

    You're good at explaining! Thank you

  • @Googlrr
    @Googlrr Жыл бұрын

    Hey man thanks so much for the videos. New to game dev but not necessarily programming and I really like these short digestible vids that help me get my mind in the right place for how game loops work. Really easy to follow. Appreciate the effort you put into these vids!

  • @BrianHaw-qj5zj
    @BrianHaw-qj5zjАй бұрын

    Hi, your video is amazing. I'm still learning regarding state machine and will be watching your other videos, I just want to say thank you for your amazing discussion.

  • @boerbol9422
    @boerbol9422 Жыл бұрын

    Why did I not found this gold mine channel before???? >>> This video is A GEM!!!

  • @JosephEelman
    @JosephEelman2 жыл бұрын

    aw man this is awesome, these tutorials of yours are super underrated

  • @TheShaggyDev

    @TheShaggyDev

    2 жыл бұрын

    Thank you! Glad you like them!

  • @yayvey
    @yayvey6 ай бұрын

    That segment about "Life without state machines" was me jsut now trying to make my first player controller with a double jump. i thought to myself that there HAS to be a way to do this more efficiently, and found your video. I'm trying to apply my web dev knowledge into game dev and it's hard as hell. Thank you for this video lmao.

  • @riisezz0
    @riisezz02 жыл бұрын

    I've been looking for a decent video on general state machine theory for a while and was wondering why I hadn't come across this ages ago. It's because you're new! *Sub* Thanks! Great stuff!

  • @TheShaggyDev

    @TheShaggyDev

    2 жыл бұрын

    Thanks for subbing! Glad I could help!

  • @chastor1961
    @chastor196111 ай бұрын

    oh, god This is one of the best tutorial Ive ever seen , your fantastic bro keep moving, I sub without hesitation 👌👌 , good job

  • @alejandroalvarezpaneca1637
    @alejandroalvarezpaneca1637 Жыл бұрын

    very very useful. just what i was looking for .

  • @kojokiller998
    @kojokiller9982 жыл бұрын

    Criminally underrated channel. Just wait bro, the subs are coming.

  • @jamesrichards9981
    @jamesrichards99818 ай бұрын

    Your teaching method is flawless. I'm a potato brain and I understood like 95% of this. Has me excited to get to trying this in Godot

  • @dueddel
    @dueddel2 жыл бұрын

    Instant subscription! Awesome tutorial, keep up! :)

  • @TheShaggyDev

    @TheShaggyDev

    2 жыл бұрын

    Thank you and welcome aboard!

  • @SunnyShuklathedoctor
    @SunnyShuklathedoctor5 ай бұрын

    Thanks for the great game dev class, should pay you for it so good thing i have KZread premium

  • @simonjkendrew
    @simonjkendrew11 ай бұрын

    Great video!

  • @SBimon155
    @SBimon155 Жыл бұрын

    Incredible video. Very compact and informative! Just like you said I was seemingly already using a frankensteined version of this in my game that somewhat worked but still made a lot of problems. Well, time for some refactoring :D

  • @slaxis88
    @slaxis88 Жыл бұрын

    Cool video, I've created a custom StateMachine and State Nodes, and adding new states is about creating new state child nodes to the state machine nodes. If the states are not memory intensive you can instance all of then instead of creating / destroying on the fly and just switch true / false to their physics process and input functions.

  • @TheShaggyDev

    @TheShaggyDev

    Жыл бұрын

    Yep! That's how I do it in Godot, as well, but wanted to present the more "classic" take on state machines in this video since I wanted to keep it a bit engine agnostic, though you could probably get away with a similar design in just about any engine...

  • @historish165
    @historish1652 жыл бұрын

    Thank you for this incredibly detailed video. Is there any chance in future you would consider making them without the music in the background? i find it super difficult to learn/concentrate on something new in a logical manner when music is playing. I'm sure there're more folk like me who struggle with the ADD side of things. If not, there's always mute and closed captions =D

  • @TheShaggyDev

    @TheShaggyDev

    2 жыл бұрын

    I'm certainly open to it if there's a broader interest in videos without music. For what it's worth, I started turning down the music more after my state pattern videos, and I may try going lower in the future or changing songs as I'm still dialing in things on the channel. Do you still find the music distracting in my more recent videos?

  • @moska1339
    @moska13392 жыл бұрын

    Your content is very good!

  • @TheShaggyDev

    @TheShaggyDev

    2 жыл бұрын

    Thank you! I'm glad you've found it useful!

  • @maiqtheliar2611
    @maiqtheliar26118 ай бұрын

    thank you so much...!

  • @terry-
    @terry-4 ай бұрын

    Great!

  • @panampace
    @panampace Жыл бұрын

    A state machine is a MUST for a character controller. “Cleaner, easier to maintain, and easily expandable with little effort” is true. I wasted so much time thinking a state machine is too complicated, it’s actually way more simple than one big messy controller script.

  • @Legit_SuperFall

    @Legit_SuperFall

    5 ай бұрын

    Im having some problems with my player controller, but im weary of using state machines because the player movement is very complex and interconnected..

  • @hoppalapasam53
    @hoppalapasam532 жыл бұрын

    Thank you, this will help Me out for optimization of enemy ai for.my.game.

  • @curkas
    @curkas2 жыл бұрын

    Still a little over my head with the jargon - but I like your voice. It makes me feel like I'm getting it more than I am :P

  • @TheShaggyDev

    @TheShaggyDev

    2 жыл бұрын

    Haha, well if there's anything I can clarify feel free to ask.

  • @compasscrafting1147
    @compasscrafting1147 Жыл бұрын

    Great presentation and easy to understand. Subscribed. One thing I had a question about was the final section on cleaning up the Jump state exit() function by creating a Base state which holds the exit() function. Does the "requirement" to call exit() from Jump state warrant the work to create the Base state if you were working on a project? Are there other states you could imagine "needing" to exit() that you would not want to duplicate code on? Or is it for the purposes of following good practices?

  • @TheShaggyDev

    @TheShaggyDev

    Жыл бұрын

    Thanks! At a basic level, having the BaseState there to hold a base implementation of each function really just means you can always call "some_state.exit()" and not have to do something like "if some_state.exit: some_state.exit()" to do so without breaking your code in case you don't implement that function somewhere. Going a bit deeper, though, an exit function is a pretty standard part of a state pattern implementation that you'll want to have around just in case, and since the interface defined in this video says there's an exit function, we need to define that on every state, even if it's a simple no-op. In languages lacking the concept of an interface, like GDScript, this has the extra benefit of helping with code completion and type checking.

  • @ThunderThoster
    @ThunderThoster Жыл бұрын

    We are standing on the shoulders of giants... one apple man once said.

  • @3XC4L1B3R
    @3XC4L1B3R3 ай бұрын

    Can confirm, I did implement something resembling that enum. But it started feeling messy, so here I am. 😅

  • @KulaGGin
    @KulaGGin2 ай бұрын

    "Most have never heard of" Learned it, implemented it(the proper OOP GoF State Machine design pattern) in my own projects(not game dev). Now looking into how to implement it well in UE. It's very badly implemented in UE where it only supports it for the animations(either mesh or sprite animations) but not the full player state machine where we can handle inputs properly, play animations, sounds, etc.

  • @Kaedric999
    @Kaedric9992 жыл бұрын

    good vid, looking forward to part 2

  • @TheShaggyDev

    @TheShaggyDev

    2 жыл бұрын

    Thank you! I'm currently wrapping up editing part 2 so that should be out in another day or two.

  • @joggerjoe
    @joggerjoe2 ай бұрын

    i love state machines. but have some trouble when it comes to more complex or overlapping states. for example if u have a swimming or climbing state. you can jump when climbing or leaving water. but its an other jump then from ground. what about if u want to separate jump-state into jumping, inair and landing to do something like coyote timer or different animations. next issue i have is the reusability of states for other characters that maybe cant jump. there is a hard coupling between states. evenry state needs to know at least the possible target-states. sorry for that many questions xD anyways, great video.

  • @TheShaggyDev

    @TheShaggyDev

    2 ай бұрын

    Yeah, how quickly the complexity can grow is the biggest problem with state machines, imo, and I find it hard to give recommendations on that because it can vary so much depending on what the project needs (similar states just playing a different animation vs completely different rulesets, etc). There are some techniques for making it better, like hierarchical machines or moving logic to external components, but it gets tricky.

  • @taintedmyth0s636
    @taintedmyth0s636 Жыл бұрын

    I'm super confused about where/how to add the initial State interface. I keep getting errors and the documentation isn't helping :(

  • @TheShaggyDev

    @TheShaggyDev

    Жыл бұрын

    Sorry for the confusion! A bit of clarification is needed here. So this video is intended as a theoretical introduction to state machines, but not an implementation guide. The first half being why you should care and what the high level structure should look like while the second half, where I start talking about interfaces and so on, is intended for more experienced programmers to learn how to make their own agnostic of the engine. If you want to see how to make one in Godot, I've got two videos on the subject, starting with this one: kzread.info/dash/bejne/dKFn1bSxdMWZmtY.html Give that a try and let me know if you have further questions. Happy to help, and sorry again for the confusion!

  • @taintedmyth0s636

    @taintedmyth0s636

    Жыл бұрын

    @@TheShaggyDev That makes sense, thanks! It was definitely really useful for understanding the theory behind a state machine, though I already know that since I'm coming from another engine (Roblox Studio, though my friend was the one who made it on there) but it was a good step in the right direction for figuring out how it'd work in Godot!

  • @TheShaggyDev

    @TheShaggyDev

    Жыл бұрын

    @@taintedmyth0s636 Awesome! Glad to help 🙂

  • @bubblemage
    @bubblemage Жыл бұрын

    ngl i had trouble following the video because all the images were static and i had to go looking for what changed after you swapped an image showcasing code

  • @JayJay-ki4mi
    @JayJay-ki4mi Жыл бұрын

    The diagrams for state machines are not called flowcharts, but instead statecharts or state transition diagrams

  • @nathnolt
    @nathnolt Жыл бұрын

    I would stay in the enumerator pattern rather than in the state pattern, even for complex logic. Maybe if there were nested states I'd opt in for an abstraction, but probably also with an enumerator within another enumerator, but in a different class or something.

  • @TheShaggyDev

    @TheShaggyDev

    Жыл бұрын

    Totally reasonable! I tend to bounce around techniques based on how much I'm trying to manage, but don't really go as deeply OOP as this more "traditional" version of the pattern does. Whatever keeps you away from 10k if statements when a button is pressed!

  • @luigisake
    @luigisake Жыл бұрын

    1k th like lesgooo

  • @Korn1holio
    @Korn1holio Жыл бұрын

    3:41 "Can only be at one state at a time" - what about "Jump" + "Attack", or "Move" + "Jump"? I understand you'll explain it later, but it's a bit confusing for a beginners.

  • @panampace

    @panampace

    Жыл бұрын

    It’s common for states to overlap in some functionality. In my game, “Run” and “Jump” states both call the same “move character with joystick” function that I set up in the Base state. For attacks, depends on your design. Maybe your attack is always the same and doesn’t interrupt movement, so it can be a shared function. Or maybe your ground attack is different from your air attack, so they both get their own states.

  • @GhamPlays
    @GhamPlays11 ай бұрын

    State state state state. And that's it.

  • @hyperspace2752
    @hyperspace2752 Жыл бұрын

    lmao when I was starting out, I use phases, as like in Magic the Gathering. So when I found out about FSM, I was like hol up , this basically the same thing I was doing since I was 12 yrs old lols

  • @matiturock
    @matiturock Жыл бұрын

    Hi! please use monospace fonts :D

  • @praveenkumar136
    @praveenkumar136 Жыл бұрын

    Very educative video but background music is very annoying. May be I am not a game developer so that why I am annoying Awesome video !!!

  • @ForgivenessOfGodAlMighty
    @ForgivenessOfGodAlMighty2 жыл бұрын

    this video is super helpfull thank you so much PS : youtube algorithme sucks

  • @TheShaggyDev

    @TheShaggyDev

    2 жыл бұрын

    Thank you! I'm glad you found it useful!

  • @robertonome2448
    @robertonome24482 жыл бұрын

    still can't figure out why people would ever *not* use state machines... I mean, if you're using a basic engine like construct it's kinda excusable, but for ones like Unity, Godot (which I have a slight impression that it's the one you use too), and Unreal, you're definitely a masochist

  • @TheShaggyDev

    @TheShaggyDev

    2 жыл бұрын

    Right? I still see people on the Godot subreddit, for instance, just about every week trying to solve a problem a state machine would solve or at least make a whole lot easier to fix.

  • @robertonome2448

    @robertonome2448

    2 жыл бұрын

    @@TheShaggyDev pretty much hahah kinda of a trend to wrap your head around problems that have been solved decades ago in these game dev forums... only shows how little value people, in general, give to the documentation of the tools they use.

  • @realMenta

    @realMenta

    Жыл бұрын

    I think the only other reason is if your problem is really simple and implementing a state machine would just make things more confusing in code.

  • @badunius_code
    @badunius_code Жыл бұрын

    8:05 I'm a bit concerned that you are coupling the states, making state change logic less transparent and making every state dependent on knowing of other states existence

  • @TheShaggyDev

    @TheShaggyDev

    Жыл бұрын

    Unless I'm misunderstanding what you're saying, it should just be that each state knows about the states that it can transition to. At the level of switching states, the code shouldn't know, or care, about what specific state is being transitioned to.

  • @badunius_code

    @badunius_code

    Жыл бұрын

    @@TheShaggyDev in some languages this may create a circular reference: StateA imports StateB to instantiate it, and StateB imports StateA for the very same reason. Also this turns transition map into a treasure map, where you have to travel all the state implementations to discover how they work. And to change transition map you have to change multiple states and not forget even one of them otherwise the map is broken.

  • @TheShaggyDev

    @TheShaggyDev

    Жыл бұрын

    @@badunius_code That circular reference issue is a fair point, and one that has bitten me with Godot 3 in the past 😅, though not specifically with state machines. But you could certainly implement a different way, I just presented one of the generic, traditional implementations I've seen to keep things fairly language and engine agnostic. Having each state manage its own transitions doesn't bother me, but I'm not going to pretend like it's the only way to do things.

  • @totheknee
    @totheknee2 жыл бұрын

    You go from the original horrible mess of _if_ statements (which motivates the need to find something better), directly to the best solution of a list of states (enumerators) + all the variables you need to switch between the states. Short, simple, maintainable, easy to debug, easy to read, easy to comprehend, easy to implement, easy to explain, does exactly what you want and no more. Perfect! Done! Right? Nope: Then you go backwards _two_ steps to an even _more_ horrible mess than the original! Full of unnecessary complications, indirectness, and orientationism. It becomes hard to debug, hard to read, hard to explain (nearly half the video vs 1 minute for enumerators!), hard to maintain. Ugh. 😣 By the way, I added a like to the video because: A) The first half was great! B) I can't blame people for falling for the OO propaganda as it has been indoctrinated into the entire programming population since probably before you were born. I know I sure fell for it...