When should you use a Finite State Machine?

  Переглядів 38,269

GDQuest Q&A

GDQuest Q&A

Рік тому

For more gamedev videos, subscribe to GDQuest: / gdquest
Here, I answer your quick questions about Godot and game development in simple videos.
If you have a question that we can answer in 5 minutes max, ask away!

КОМЕНТАРІ: 67
@GDQuestQA
@GDQuestQA Рік тому
To learn how a state machine works exactly and how to code one in Godot (non-beginner level), check out our guide on the GDQuest website: www.gdquest.com/tutorial/godot/design-patterns/finite-state-machine/
@programaths
@programaths 9 місяців тому
And FSM can be implemented in different ways. With nodes, with functions returning the next state, with a transition table, with a big switch... Each has their pro and cons!
@Max-gm2un
@Max-gm2un 8 місяців тому
​@@programathsYeah, I really liked the implementation from "the shaggy dev"
@programaths
@programaths 8 місяців тому
@@Max-gm2un Too lazy to look that up. What does he do ?
@Max-gm2un
@Max-gm2un 8 місяців тому
@@programaths He made it so that either the input or physics process Funktion will return a new state (The new state is a node assigned via an export var). It's really worth checking out! He has 3 videos, one where he explains the pattern and then two where he implements it in Godot
@VicKraz1
@VicKraz1 Рік тому
I think that state machines makes everything easier the more states the player has. If I just code a character that can be idle, run and jump the state machine can be unnecessary. But when more states are added the state machine helps a lot.
@TheBugB
@TheBugB 8 місяців тому
Yeah I pretty much agree. But even for a simple object you can use a basic version in 1 file using something like an enum to track states.
@ViolentFury1
@ViolentFury1 4 місяці тому
with state machine how do you handle situtations when player is jumping, is on fire, is taking damage ?
@anthonyec
@anthonyec Рік тому
There's nothing about the state machine pattern that says you need to split things into multiple files and nodes. The pattern is about having a set finite states a system can be in. At it's most basic, one state at one time. So you could still have a bare bones implementation of a FSM in a single file with no boilerplate. Example: a switch statement that checks a string of the current state
@PaulSpades
@PaulSpades Рік тому
Yeah, this answer assumed each state is a node and a class. I don't know why. You can have states as enum or dictionary or array... any list-type data structure, instead of a list of child nodes. What makes it a state machine is that you define the progression between states so that a) the current state is always only one of the defined states and b) never undefined.
@BrotherCarl
@BrotherCarl 7 місяців тому
This is what I've done with mine. Instead of a string I'm using an enum
@hiiambarney4489
@hiiambarney4489 Рік тому
There comes a point in your Character Controller, no matter the gameplay or 2D,3D variations where a State Machine is pretty much mandatory. That point gets closed in by adding features. The more different things your Character needs to do, the more you should invest in a State Machine, best case is you have Design Doc ready for you and really, reaaaaally think about this beforehand, what your Character needs so you know before hand if you have to implement a state machine or not but here are some pointers: State Machine make things like Jump Buffers and Coyote Timers, Separate Air and Ground Attacks, Combo Strings and all the stuff that is more advanced than 99% of all youtube game dev tutorials out there (because usually the creator lacks the skills to implement these themselves), fairly trivial to progress and debug. If you want to make anything more advanced than Megaman or Mario Bros., for example Megaman X or Super Mario, a State Machine is pretty much a must, for your own sanity. Don't think of it as extra lines of code but rather time saved having to debug it later on (and ease of use but the debugging alone would be enough) You can easily tell if you need a State Machine if you ever look at your code and think to yourself "Damn, I gotta add another Boolean for this Attack... AND THEN ANOTHER ONE FOR SLIDING..."
@s_qadoome2153
@s_qadoome2153 2 місяці тому
you explained my whole experience at the end
@alfonsov3190
@alfonsov3190 Рік тому
Thank you for the video. I was just yesterday trying an FSM for a character, and it does complicate things for me to have to gather references from everywhere for it to work properly. What I would suggest from my experience is to start with the simplest method and then, as the need for using a different one increases, start rearranging your code.
@WillTaplin
@WillTaplin Рік тому
Those two projects look great! Part of some new courses? I love GDQuest courses!
@RickRodGaming
@RickRodGaming 5 місяців тому
When I started with programming a 2D Platformer, I used to have all the movement in a single script. It was functional, but buggy and I couldn't really expand it. Using a state machine helped me separate a good flow on when I want to send the character to a certain state, that allows specific type of movements.
@ayushsidam289
@ayushsidam289 Рік тому
Thanks sir for the video. 😀🙌🏻 This video is really helpful for the beginners like me even though I'm learning unity for game development .
@robthegnat9697
@robthegnat9697 Рік тому
I'm not really a game programmer. I hobby at it, but I really like state machines. The thing I take with me from my day job is unit testing and making thing generic. It becomes a lot easier to add testing to a smaller script. I think I was jarred in my earlier programming experience. I was working on a MFC program and my one class was over 10k lines. They didn't know about inheritance. Ever since then, I've always tried for short classes that can be reusable and generic. For instance, you have a move class. The goblin and the knight can use the same class. You just have to pass in the animation. As long as you make it generic, you'll be all set. Then, you have one test case that handles all of the characters. One code (ring) to control them all. :) I'll have to watch your other video. I haven't really looked at that. I like what you have and it is very interesting.
@fourplenty
@fourplenty Рік тому
Great insights on state machines in Godot
@KingThrillgore
@KingThrillgore Рік тому
In 3D at least, I think state machines for animation make a lot of sense. It's the defacto Animation method in Godot, Unity, and Unreal for a reason. But the more states you need for AI, the greater the overhead and the difficulty of maintenance, which is what planning AIs alleviate. Planning based AIs have a lot more complexity and over-time performance qualms though.
@drbuni
@drbuni Рік тому
I find that FSM makes the code more readable to me, so long as the object is complex enough to warrant it, such as the player in my project who has a bunch of different states (idle, move, jump, spin jump, block, melee attack). Enemies, on the other hand, are simple enough that I don't see any reason to use FSM. As for bosses, I want to learn the approach Pigdev suggested in one of his videos. That is, to use the AnimationTree node to more easily create a complex state machine. I am still a beginner, of course, so everything I say might change in a week.
@lucuinhas
@lucuinhas 7 місяців тому
have you released the project for this already so i can cop- i mean, borrow it lol
@SteinGauslaaStrindhaug
@SteinGauslaaStrindhaug Рік тому
While I understand it's not so, this video kinda made it seem like the main difference between the approaches is one-big-file vs. many-small-files which is not at all the main difference. How to split code in files is usually just a convention not a hard rule (unless this specific language/engine enforces such a convention). I'm sure you could in principle put all the states in one file, and split the non-FSM code into multiple files as well (though, that might be slightly harder if it's all very interconnected). I must say I never really understood the advantage of state machines when I was taught it in university or even the big difference compared to equivalent code that is not a state machine (beyond surface level details such as how you organise code). Also they seemed to grow incomprehensibly large very fast. The state machine for two buttons is easy enough (but any controller for just two buttons would usually also be pretty easy), but with just a handful of inputs the state graph becomes gigantic network pretty fast; sure that complexity is there in any simple iterative or event based approach too, but with state machines all that complexity is reflected in huge amounts of code a little for every possible state, isn't it?
@GDQuestQA
@GDQuestQA Рік тому
The main benefits to me are as highlighted in the video: - It's easy to debug, add, or remove each of the character's behavior for example. - You generally get a high-level visual representation of the entity's behavior. This is powerful with plugins like Playmaker in Unity that are designer-friendly. - The code organization part, you can divide and conquer (but there are alternatives, of course). I wouldn't call the code organization part a surface-level detail as it helps some people to keep track of their code, as you'll read in other comments. And developers being able to process and work with their own code months down the line or teammates' code is valuable. From experience, I'd say that this pattern, paired with visualization, is especially useful when you have designers on the team.
@GDQuestQA
@GDQuestQA Рік тому
Oh, importantly, it's very useful for animation graphs, especially in 3D and when you need to control transitions and animation blending. In Godot, this feature comes built-in. It's part of the AnimationTree node. It's a good example of the pattern used to make powerful tools (because you generally need a fixed set of animations and a fixed set of allowed transitions).
@farrenLP
@farrenLP Рік тому
from the course i follow the state machines should be better for performance because when you switch states, only the code in the given state is being run. when you put all functions into one file everything is being run even if you don't need it to run. First example that comes to my mind is when character enters a vehicle and you have a function that checks each frame if any enemies are nearby so you can target them. You don't need to do it in driving state so it would be pointless to run the function. Of course you can put IF statement that checks if you are in a car but it still takes a small portion of a performance and makes you write more lines of code
@SteinGauslaaStrindhaug
@SteinGauslaaStrindhaug Рік тому
@@farrenLP but how does the system decide which state machine is running? In any case there's a conditional jump in the machine code somewhere. But maybe that's the point, it's not an actual functional difference down in the assembly level assuming either style is written sensibly and optimized well, the difference is just in how the code feels to work with in high level?
@Ombarus
@Ombarus Рік тому
I don't like FSM because you'll nearly always end up having to be into multiple states at once (running and attacking for example). There are workarounds but it becomes messy quickly. I prefer the second method but I would still split things up by separating them in Components or Layers that live in a list and are applied sequentially every frame. Then you can have many of those "Layers" active or disabled and use composition to create the behavior you want.
@GDQuestQA
@GDQuestQA Рік тому
Yeah we split into multiple parts but favoring aggregation whenever possible. We like to favor the most basic abstractions first and avoid adding our own structural patterns. But your solution sounds good too.
@sslaxx
@sslaxx Рік тому
Makes me wonder if the animation players could be used to handle it in part, considering one of them has a built-in state machine (and if you've seen Aarimous's or Furcifer's videos, AnimationPlayer is far more powerful than most people realise).
@skaruts
@skaruts Рік тому
I've been through this myself. I ended up tending to think actions aren't states in the first place. I don't usually implement FSMs in my own characters until I really have to, but then it's never for actions. Actions can just be functions. In a car game prototype I have three states as an enum (I don't do FSM states as nodes): *NORMAL* - for regular gameplay *RECOVERING* - when you crash, you press a key to recover (like Carmageddon) - controls are deactivated for the duration of this state (until all wheels are touching the ground) *DEAD* - when the car has been destroyed and is no longer doing anything That's the kind of thing I consider to be states.
@rambosweat
@rambosweat Рік тому
what's a general best practices strategy for syncing state machine state in a server-centric multiplayer game?
@fruitdudetv
@fruitdudetv Рік тому
uhh i wish i could see the full code for the 2D one shown here. i always struggled hardcore with the animation implementation in a FSM :(
@bubblemage
@bubblemage Рік тому
So what about the state machine that uses animations? is that node useful too? Also one fear I always have when making a long long script is doing physics stuff, because I always think EVERYTHING related to physics must go inside the _physics_process func, but that is not the case it's just for syncing everything better, so I never know what to do in those cases.
@bigenough2122
@bigenough2122 Рік тому
Thanks❤ Please tell us about the factory pattern in Godot) How to use it to create a player, enemies, how to passed the dependencies necessary for these objects
@GDQuestQA
@GDQuestQA Рік тому
Would you have a concrete use for it? It's a pattern I rarely find necessary or useful in Godot as you can instantiate scenes and tweak their properties already. I've used it maybe once or twice for rare cases in Godot.
@bigenough2122
@bigenough2122 Рік тому
@@GDQuestQA Let's take an example of creating a top-down shooter. To create an enemy, I need to have his characteristics (level, damage, armor), his position on the map, a link to the player (for example, to move in his direction) and possibly other links to services. All this can change depending on the level of the map and the type of monster. I assume that the "Factory" is an "entry point" that accepts a list of dependencies that will be passed to the monsters being created. I don't have any experience in Godot development, maybe I'm overcomplicating :)
@GDQuestQA
@GDQuestQA Рік тому
@@bigenough2122 You don't need the factory pattern to do that in Godot, yes, the pattern would likely complicate things.
@bigenough2122
@bigenough2122 Рік тому
@@GDQuestQA Please tell me how I can get a link to the player?) get_tree().root and search in child nodes 'Player node'?
@GDQuestQA
@GDQuestQA Рік тому
@@bigenough2122 Here are four options: - The object instancing the monsters can provide the reference to the player when spawning new monsters. - You can add your player to a node group and use get_tree().get_nodes_in_group("...") - You can make an autoload (singleton) with a function get_player() that anything that needs a ref. to the player can call - If you don't want to use a singleton, you can make a class that extends Resource, load it into your monsters (loading the same resource in multiple places in Godot only loads it once, loaded resources are cached), then acquire a reference to the player in the resource. This gives you precise control over what has access to the player.
@aidanmelendez7201
@aidanmelendez7201 Рік тому
I noticed that States are nested under what looking like a parent State, how is that handled? are those states acting like a sub-StateManager? for example you have a Movement state with Ground, Air and Ladder States under it. Im not sure I understand how this works.
@sm5574
@sm5574 4 місяці тому
Finite state machines are more flexible. That is almost always a major benefit.
@saturn7_dev
@saturn7_dev Рік тому
Yes, I have questions big time - I have a 70% completed 3d game in a different game engine (much older) done in javascript (1,000 lines of code) and thinking of using a better game engine with more features like Godot. I dont wish to split my code up into chunks but rather keep it as one whole. Is it better to use Godot javascript or Gdscript and can this be done without too much trouble ? Seesm from this video you can do just that and do you have a template example I can see how to setup this ?
@puzzud
@puzzud 5 місяців тому
Not technically possible in Godot, because of where data is sourced. But technically you can get fairly close (2 source files)--probably close enough for a madman who'd like it that way. I suppose you'd still be able to reap the benefits of the game engine. But I don't think anyone would recommend doing it this way.
@FaeKitty
@FaeKitty Рік тому
What demo/course is the 2d example from?
@armyofchickens6062
@armyofchickens6062 Рік тому
Would this work for a 2d top down game in godot v4.0?
@googleyoutubechannel8554
@googleyoutubechannel8554 2 місяці тому
Public service announcement: For anyone watching this, I would recommend ignoring this video entirely, there are so many layers if misunderstanding, the vid doesn't capture the fundamentals of what a state machine is, godot doesn't implement actual finite state machines, what they are and their benefits/tradeoffs are not mentioned.
@FaeKitty
@FaeKitty Рік тому
What demo/course is the 2D example in your video from?
@GDQuestQA
@GDQuestQA Рік тому
It's a still unreleased demo, we're working on a bunch of character controllers to open source around Godot 4's release.
@FaeKitty
@FaeKitty Рік тому
@@GDQuestQA That sounds really great. I'm looking forward to it. Are you folks working on any new Godot courses?
@GDQuestQA
@GDQuestQA Рік тому
@@FaeKitty We're getting started with Godot 4, yes. We have two large projects that'll likely be running throughout 2023.
@adventuretuna
@adventuretuna Рік тому
To me FSMs are a no brainer. I even use it to control UI. You just need to know how to use it properly.
@ugliBoro
@ugliBoro Рік тому
in the video, state-machine has a weird icon... is it node or it came from script? May I know what it is..
@BravosChannel
@BravosChannel Рік тому
You can make plugins that allow you to register icons for custom nodes
@ugliBoro
@ugliBoro Рік тому
@@BravosChannel aah! good thing to know. Well, I'm just starting out so i don't think i should consider doing such. Let me sick with my basics. Thanks!
@BravosChannel
@BravosChannel Рік тому
@@ugliBoro all good! Custom icons are usually really good when you start doing larger scale projects that utilize a lot, or reusing code from multiple projects, so sticking to basics is good! (I wish there was a way to use custom icons without having to use plugins though, there's probably a feature request in GitHub somewhere, there's also probably a lot of design considerations involved)
@ugliBoro
@ugliBoro Рік тому
@@BravosChannel Man that sounds scary... last week was rough enough to do one tutorial. Now plugins and stuffs... I should probably stick to core.
@gravitronlocksport9925
@gravitronlocksport9925 Рік тому
@@BravosChannel No need for all that, you can set an icon for a class when defining it. extends Node class_name MyClass, "path\to\icon.svg" In Godot 4 the syntax will be changing slightly extends Node class_name MyClass @icon("path\to\icon.svg")
@joshsera
@joshsera Рік тому
That example of not using a state machine is still using a state machine, just a terribly implemented one. A huge if/then statement with dozens of clauses inspecting dozens of different variables is a nightmare to understand, and horrific to debug, plus as things become more complicated, the gigantic if/then just keeps growing, and then people fall into the sunk cost fallacy, so it never gets replaced with something more undertstandable. PLUS the logic is exactly the same, just worse. Another benefit is being able to use the same state for different characters if you write things correctly. It's easier to have two characters with slightly different lists of behaviors using a bunch of classes, rather than writing out big if/then statements in both of them. While using an if/then statement may save you time initially, it will eventually become a maintenance nightmare. I know this from a lot of experience. I worked at a game company for a week where the lead dev had written a gigantic if/then statement with probably 50-60 clauses that each looked at variables scattered throughout the code in random places. I quit quickly because the idea of staring at that mess of spaghetti every day made me want to cry.
@GDQuestQA
@GDQuestQA Рік тому
The state pattern is specifically about swapping objects representing states. So no, the imperative code example is not still using the pattern. Or, if you'd like, it's a state machine in the sense that every computer program is a state machine, but that's it. Regarding the rest, well, it depends on the code size. In your comment, you seem to assume every script has to grow very big and complex, while in most indie Godot games, you'll tend to have many manageable scripts. And you can always refactor. Code becomes a nightmare to manage when you can't keep technical debt in check, but in our team we edit and rewrite things as needed. Actually as a lead, I make sure my teammates understand and can edit each other's code. This code you've seen, even the most junior in my team has no problem with. If we have trouble with code the team needs to edit, we'll always refactor.
@harrysanders818
@harrysanders818 6 місяців тому
Amen. Advising people to "try out this giant blob of code" just for the convenience of not having to jump between different scripts (something that is easily done in IDEs like Visual Studio) makes me question the formal programming education of this channel
@juiceman7649
@juiceman7649 Рік тому
I just don't know if I should do my state machines all in code or if I should use the animationnodestatemachine I like the node one but am struggling to get it to do exactly what I want what would you guys recommend ?
@esdrascaleb
@esdrascaleb Рік тому
I made an abomimation that is a blob code with stat machine because the animations are state but the player code is a blob
Do This Instead Of Representing State With Booleans
12:23
Joy of Code
Переглядів 113 тис.
Сын Расстроился Из-за Новой Стрижки Папы 😂
00:21
Глеб Рандалайнен
Переглядів 5 млн
Спектакль для окупантів та ждунів 🤯
00:47
Радіо Байрактар
Переглядів 558 тис.
How NES Games Use State Machines For Everything
8:21
NesHacker
Переглядів 29 тис.
Best FREE Software for Game Development in (2024)
8:01
anyDev
Переглядів 23 тис.
How to Code (almost) Any Feature
9:48
DaFluffyPotato
Переглядів 620 тис.
Building a more advanced state machine in Godot 3
6:53
The Shaggy Dev
Переглядів 44 тис.
A Game-Changer for the Godot Engine
2:58
StayAtHomeDev
Переглядів 55 тис.
Programming a BETTER state machine
10:16
iHeartGameDev
Переглядів 57 тис.
Which AI Behavior Framework Should You Use? | AI Series 46
17:26
LlamAcademy
Переглядів 32 тис.
How to Use a STATE MACHINE in Godot
12:50
DevWorm
Переглядів 11 тис.
Сын Расстроился Из-за Новой Стрижки Папы 😂
00:21
Глеб Рандалайнен
Переглядів 5 млн