0 votes

Doing FSM and sometimes you want the same logic to be applied for multiple states, for instance, aiming a weapon should be allowed when the player is idle, walking or running.

For such common situation normally I would do, as you guessed:

#AIM WEAPON - logic
func Something_Foobar() -> void:
  if STATE == "IDLE" or STATE == "WALK" or STATE == "RUN": pass
    # Allow aim weapon code check.
      # Allow firing weapon.

How I would go about on doing them like this: if STATE == ("IDLE" or "WALK" or "RUN"): or better even if STATE == ("IDLE","WALK","RUN"): or the inverse if ("IDLE" or "WALK" or "RUN") in STATE:

I would avoid using (arrays or dictionaries or for) loops just for this.

Thanks for reading,

Godot version v3.3.3.stable.official [b973f997f]
in Engine by (373 points)

3 Answers

+3 votes
Best answer

Arrays seem to be the correct answer here

if STATE in ["IDLE","WALK","RUN"]:
by (5,188 points)
selected by

Oh~ just remembered. Since you're doing FSM you can also use match

match STATE:
    "IDLE", "WALK", "RUN":
        # Allow aim weapon code check.
        #allow reload check
        #do only walk related stuff

Pay attention to the "WALK" STATE being used multiple times
And this can also be all placed in one line if you're one of those fanatics

+2 votes

In addition to the array suggested by Wakatta, a second alternative would be using match, especially if you've got more than one group with specific code:

match STATE:
  "IDLE", "WALK", "RUN":
    # Code when standing on the ground
  "JUMP", "FALL":
    # Code when in the air
  "SWIM", "FLOAT":
    # Code when in a liquid
by (234 points)
+1 vote

The previous answers are great but I've got two more approaches:

1) OOP with inheritance:

This can handle transitioning states and general behaviour without branching at all.

Tutorials here: https://www.gdquest.com/tutorial/godot/design-patterns/finite-state-machine/ and here https://docs.godotengine.org/en/stable/tutorials/misc/state_design_pattern.html

2) Enums:

This is a numeric value so less than operators could be an easy solution.

by (2,087 points)
Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read Frequently asked questions and How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to [email protected] with your username.