immersive-home/app/lib/utils/state_machine/state_machine.gd

41 lines
937 B
GDScript3
Raw Normal View History

2023-12-19 00:15:48 +02:00
extends Node
2024-03-17 01:14:31 +02:00
## Abstract class for a state machine
class_name StateMachine
2023-12-19 00:15:48 +02:00
signal changed(state_name: String, old_state: String)
@export var current_state: Node
var states: Dictionary = {}
func _ready() -> void:
for state in get_children():
states[state.get_name()] = state
state.state_machine = self
if state != current_state:
remove_child(state)
await get_parent().ready
current_state._on_enter()
2024-03-17 01:14:31 +02:00
## Change the current state to the new state
2023-12-19 00:15:48 +02:00
func change_to(new_state: String) -> void:
if states.has(new_state) == false:
return
var old_state = current_state.get_name()
current_state._on_leave()
remove_child(current_state)
current_state = states[new_state]
add_child(current_state)
current_state._on_enter()
2024-01-16 16:00:30 +02:00
changed.emit(new_state, old_state)
2024-01-25 17:29:33 +02:00
2024-03-17 01:14:31 +02:00
## Get the state with the given name
2024-01-25 17:29:33 +02:00
func get_state(state_name: String) -> Node:
if states.has(state_name) == false:
return null
return states[state_name]