Enum State Machine

Godot Version

4.3

Question

Hi I’m wondering how I could make a simple code based state machine using enum. If someone could give me an example in code I would be very grateful.

Sounds like you’ve got all the pieces, what part about implementing this is giving you trouble?

Make your enum with the states you’d like. With a variable to track which state the node is in

enum State { IDLE, CHASING }
var state: State = IDLE

Then, in any function you need to do state-related things you can compare this variable.

func _process(delta: float) -> void:
    if state == State.CHASING:
        position += global_position.direction_to(player.global_position) * speed * delta
    elif state == State.IDLE:
        pass
2 Likes

I found this tutorial very helpful Finite State Machine in Godot 4 · GDQuest

gertkeno already gave you a great example, so you might not need it, but the tutorial does go into a bit more detail. It also includes using Nodes, which I ended up switching too when my game got more complicated, so that is worth a read.

1 Like

Thank you. It works!