StreamOverlay/lib/state_machine/state_machine.gd

45 lines
957 B
GDScript3
Raw Normal View History

2026-02-23 18:38:03 -06:00
extends Node
class_name StateMachine
@export var initial_state: State
signal state_changed(new_state: State)
var current_state: State
var states: Dictionary[String, State] = {}
func _ready() -> void:
for child in get_children():
if child is State:
states[child.name.to_lower()] = child
child.transitioned.connect(_handle_child_transition)
if initial_state:
initial_state._enter()
current_state = initial_state
func _process(delta) -> void:
if current_state:
current_state._update(delta)
func _physics_process(delta: float) -> void:
if current_state:
current_state._physics_update(delta)
func _handle_child_transition(state: State, new_state_name: String) -> void:
if state != current_state:
return
var new_state: State = states.get(new_state_name.to_lower(), null)
if not new_state:
return
if current_state:
current_state._exit()
new_state._enter()
current_state = new_state
state_changed.emit(new_state)