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

  Переглядів 45,254

The Shaggy Dev

The Shaggy Dev

День тому

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/

КОМЕНТАРІ: 75
@pedroparamo5
@pedroparamo5 Рік тому
What a fantastic lecture. There isn’t a single second wasted in it. Instant sub, I hope your channel keeps growing!
@TheShaggyDev
@TheShaggyDev Рік тому
Thank you! Glad you liked it!
@BrianHaw-qj5zj
@BrianHaw-qj5zj 9 днів тому
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.
@osayami
@osayami Рік тому
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 Рік тому
Thank you! And welcome aboard!
@bisquestudio
@bisquestudio 2 роки тому
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
@Pixelaze 2 роки тому
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
@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!
@aventurileluipetre
@aventurileluipetre Місяць тому
You're good at explaining! Thank you
@alejandroalvarezpaneca1637
@alejandroalvarezpaneca1637 Рік тому
very very useful. just what i was looking for .
@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
@chastor1961
@chastor1961 10 місяців тому
oh, god This is one of the best tutorial Ive ever seen , your fantastic bro keep moving, I sub without hesitation 👌👌 , good job
@whsquare
@whsquare 2 роки тому
aw man this is awesome, these tutorials of yours are super underrated
@TheShaggyDev
@TheShaggyDev 2 роки тому
Thank you! Glad you like them!
@maiqtheliar2611
@maiqtheliar2611 7 місяців тому
thank you so much...!
@dueddel
@dueddel 2 роки тому
Instant subscription! Awesome tutorial, keep up! :)
@TheShaggyDev
@TheShaggyDev 2 роки тому
Thank you and welcome aboard!
@simonjkendrew
@simonjkendrew 10 місяців тому
Great video!
@yayvey
@yayvey 5 місяців тому
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.
@kojokiller998
@kojokiller998 Рік тому
Criminally underrated channel. Just wait bro, the subs are coming.
@boerbol9422
@boerbol9422 Рік тому
Why did I not found this gold mine channel before???? >>> This video is A GEM!!!
@riisezz0
@riisezz0 2 роки тому
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!
@jamesrichards9981
@jamesrichards9981 6 місяців тому
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
@SunnyShuklathedoctor
@SunnyShuklathedoctor 4 місяці тому
Thanks for the great game dev class, should pay you for it so good thing i have UKposts premium
@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...
@terry-
@terry- 3 місяці тому
Great!
@hoppalapasam53
@hoppalapasam53 2 роки тому
Thank you, this will help Me out for optimization of enemy ai for.my.game.
@moska1339
@moska1339 2 роки тому
Your content is very good!
@TheShaggyDev
@TheShaggyDev 2 роки тому
Thank you! I'm glad you've found it useful!
@KulaGGin
@KulaGGin Місяць тому
"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.
@3XC4L1B3R
@3XC4L1B3R 2 місяці тому
Can confirm, I did implement something resembling that enum. But it started feeling messy, so here I am. 😅
@historish165
@historish165 2 роки тому
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?
@curkas
@curkas 2 роки тому
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.
@Kaedric999
@Kaedric999 2 роки тому
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.
@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.
@joggerjoe
@joggerjoe 28 днів тому
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 28 днів тому
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.
@ThunderThoster
@ThunderThoster Рік тому
We are standing on the shoulders of giants... one apple man once said.
@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.
@fatjesus7772
@fatjesus7772 4 місяці тому
Im having some problems with my player controller, but im weary of using state machines because the player movement is very complex and interconnected..
@JayJay-ki4mi
@JayJay-ki4mi 11 місяців тому
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!
@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: ukposts.info/have/v-deo/ep1kp4ive5hky6c.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
@matiturock
@matiturock Рік тому
Hi! please use monospace fonts :D
@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
@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
@GhamPlays 10 місяців тому
State state state state. And that's it.
@luigisake
@luigisake Рік тому
1k th like lesgooo
@robertonome2448
@robertonome2448 2 роки тому
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.
@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
@ForgivenessOfGodAlMighty 2 роки тому
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!
@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
@totheknee 2 роки тому
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...
Computers Without Memory - Computerphile
8:52
Computerphile
Переглядів 333 тис.
How NES Games Use State Machines For Everything
8:21
NesHacker
Переглядів 29 тис.
Їжа Закарпаття. Великий Гід.
1:00:29
Мiша Кацурiн
Переглядів 579 тис.
Лизка заплакала смотря видео котиков🙀😭
00:33
How to make a tactics game in only two weeks
19:00
The Shaggy Dev
Переглядів 60 тис.
How to Program in Unity: State Machines Explained
18:56
iHeartGameDev
Переглядів 207 тис.
An introduction to graph rewriting for procedural content generation
7:31
Do This Instead Of Representing State With Booleans
12:23
Joy of Code
Переглядів 113 тис.
Implementing the state pattern in Godot 3
7:44
The Shaggy Dev
Переглядів 28 тис.
How to Code (almost) Any Feature
9:48
DaFluffyPotato
Переглядів 616 тис.
Programming a BETTER state machine
10:16
iHeartGameDev
Переглядів 56 тис.
Big Tech AI Is A Lie
16:56
Tina Huang
Переглядів 34 тис.
The 7 Strangest Coincidences in the Laws of Nature
8:13
Sabine Hossenfelder
Переглядів 249 тис.
Їжа Закарпаття. Великий Гід.
1:00:29
Мiша Кацурiн
Переглядів 579 тис.