Files
tgcc/core/ai/framework/state_machine.gd

47 lines
875 B
GDScript

extends Node
class_name StateMachine
@export var initial_state: State
var current_state: State
var states: Dictionary = {}
var enable: bool = true:
set(value):
enable = value
toggle_enable()
func toggle_enable() -> void:
if !enable:
return
if !states.is_empty():
return
for state in get_children():
if state is State:
states[state.state_id] = state
state.transitioned.connect(_on_state_transition)
if initial_state:
current_state = initial_state
current_state.enter()
func physics_process(delta) -> void:
if current_state and enable:
current_state.update(delta)
func _on_state_transition(state: State, new_state_id: String) -> void:
if state != current_state:
return
var new_state = states.get(new_state_id)
if not new_state:
return
if current_state:
current_state.exit()
current_state = new_state
current_state.enter()