derkork / godot-statecharts

A state charts extension for Godot 4
MIT License
734 stars 35 forks source link

help - how to check if a StateChart is in a specific state? #40

Closed bazsupport closed 10 months ago

bazsupport commented 10 months ago

hello, love your state machine asset, but how to check if a StateChart is in a specific state in code?

for example: if body == player and player.state_chart.current_state == "idle":

i tried looking at the manual, but im still pretty novice lol any info much appreciated!

derkork commented 10 months ago

The idea behind this library is that you wouldn't need to do such checks in your code anymore. If you want to run code only in specific states then the plan would be to connect this state's state_processing or state_physics_processing signal to a function. The library will then run this function every frame for as long as the state is active.

If this doesn't work for you, I'd like to know more about your use case, so I can make a better suggestion.

bazsupport commented 10 months ago

The idea for my particular situation was for another Area2D checking to see if the player was in a particular state_chart before applying some logic. I know I could do this with a bool as well (setting it true inside a certain state and then turning it false when exiting and then checking player.bool), but I just thought there might be an alternative method for checking if state_chart.current_state == "Movement": would be a cool feature too.

derkork commented 10 months ago

The thing is that a state chart can be in multiple different states at the same time, so such a property would need to return an array. Also to produce it, one would need to walk down the whole state chart and collect all currently active states.

However you can ask each state whether it is currently active, so if you really want to you could use a scene unique node to access the state you are interested in (https://docs.godotengine.org/en/stable/tutorials/scripting/scene_unique_nodes.html) and then ask the state whether it is active. E.g

var state = %SomeState
if state.active:
    # do things

However you say that another area outside of the entity needs to know this. In this case I wonder whether it would be a good idea if the area knows about how your entity is tracking state internally. This would tightly couple the area to some implementation detail of your entity that is controlled by the state chart. I'd probably use the state_entered / state_exited events and then add/remove the entity to/from a group (https://docs.godotengine.org/en/stable/tutorials/scripting/groups.html) and let the area only check the group. This way your area doesn't need to know about state charts and if you decide to reorganize your states later it will still work.

bazsupport commented 10 months ago

I think that helps and are reasonable solutions. Thank you for the responses