Тёмный

When should you use the State pattern in Godot? 

GDQuest Q&A
Подписаться 5 тыс.
Просмотров 47 тыс.
50% 1

For an introduction to finite state machines, learning what they are, and learning two implementations in Godot 4, check out this guide: www.gdquest.co...
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!

Опубликовано:

 

1 окт 2024

Поделиться:

Ссылка:

Скачать:

Готовим ссылку...

Добавить в:

Мой плейлист
Посмотреть позже
Комментарии : 72   
@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 Год назад
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_prez555
@Max_prez555 Год назад
​@@programathsYeah, I really liked the implementation from "the shaggy dev"
@programaths
@programaths Год назад
@@Max_prez555 Too lazy to look that up. What does he do ?
@Max_prez555
@Max_prez555 Год назад
@@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 Год назад
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 9 месяцев назад
with state machine how do you handle situtations when player is jumping, is on fire, is taking damage ?
@lukanvanderlinde
@lukanvanderlinde 29 дней назад
⁠@@ViolentFury1 one approach is to separate states that don’t require to be interconnected. Like jumping is the state on the movement state machine. where on fire could be a status modifier state machine where the effect of being on fire is to take damage.
@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 7 месяцев назад
you explained my whole experience at the end
@lautaromendieta9086
@lautaromendieta9086 2 месяца назад
Hahaha totally accurate the last sentence, when I first reached that point I started to think "sure there's a better way to do this". FSM was the solution.
@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 Год назад
This is what I've done with mine. Instead of a string I'm using an enum
@googleyoutubechannel8554
@googleyoutubechannel8554 7 месяцев назад
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.
@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.
@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.
@RickRodGaming
@RickRodGaming 10 месяцев назад
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.
@WillTaplin
@WillTaplin Год назад
Those two projects look great! Part of some new courses? I love GDQuest courses!
@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.
@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.
@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?
@fuzzy-02
@fuzzy-02 2 месяца назад
Good perhaps for combat with a ton of combos like those in fighter games
@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 .
@DashMatin
@DashMatin 3 месяца назад
that project with the swordsman looks fantastic exactly how i want my game to be like Dead Cells care to make tutorials on that proj?
@アドチ
@アドチ Год назад
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.
@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.
@sm5574
@sm5574 9 месяцев назад
Finite state machines are more flexible. That is almost always a major benefit.
@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.
@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 :(
@armyofchickens6062
@armyofchickens6062 Год назад
Would this work for a 2d top down game in godot v4.0?
@lucuinhas
@lucuinhas Год назад
have you released the project for this already so i can cop- i mean, borrow it lol
@rambosweat
@rambosweat Год назад
what's a general best practices strategy for syncing state machine state in a server-centric multiplayer game?
@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 9 месяцев назад
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.
@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.
@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")
@FaeKitty
@FaeKitty Год назад
What demo/course is the 2d example from?
@fourplenty
@fourplenty Год назад
Great insights on state machines in Godot
@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.
@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 11 месяцев назад
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
Далее
Starter state machines in Godot 4
10:58
Просмотров 56 тыс.
Ко мне подкатил бармен
00:58
Просмотров 186 тыс.
#kikakim
00:10
Просмотров 10 млн
Свадьба Раяна Асланбекова ❤️
00:12
МОЮ ТАЧКУ РАЗБИЛИ...!
39:06
Просмотров 428 тыс.
Do This Instead Of Representing State With Booleans
12:23
How NES Games Use State Machines For Everything
8:21
Why I Started Game Dev In My Late 30s
7:32
Просмотров 22 тыс.
Why Solo Developers Should Use Unreal
9:51
Просмотров 387 тыс.
Programming a BETTER state machine
10:16
Просмотров 75 тыс.
Do THIS Before You Publish Your Godot Game
3:33
Просмотров 174 тыс.
choosing a game engine is easy, actually
15:08
Просмотров 503 тыс.
Ко мне подкатил бармен
00:58
Просмотров 186 тыс.