67 lines
2.0 KiB
GDScript
67 lines
2.0 KiB
GDScript
class_name StateMachine extends Node
|
|
|
|
#export (NodePath) var starting_state
|
|
export var debug_state_machine: bool = false
|
|
|
|
# I guess I would declare a number of states here
|
|
#export (Reference) var states # Doesn't work
|
|
#var starting_state: State
|
|
|
|
var current_state: State
|
|
#var state_modifiers: Array
|
|
export(Dictionary) var states :Dictionary
|
|
|
|
# Initialize the state machine by giving each child state a reference to the
|
|
# parent object it belongs to and enter the default starting_state.
|
|
func init() -> void:
|
|
# for child in get_children():
|
|
# if child is State:
|
|
# if debug_state_machine:
|
|
# print("Initializing State Node: ", child.name)
|
|
## child.modifier_stack_ref = state_modifiers
|
|
# if debug_state_machine:
|
|
# child.debug_state = true
|
|
|
|
for s in states.keys():
|
|
var this_state = states.s
|
|
if this_state is State:
|
|
if debug_state_machine:
|
|
print("Initializing State Node: ", s)
|
|
this_state.debug_state = true
|
|
|
|
|
|
# Change to the new state by first calling any exit logic on the current state.
|
|
func change_state(new_state: State) -> void:
|
|
if current_state:
|
|
current_state.exit()
|
|
|
|
current_state = new_state
|
|
current_state.enter()
|
|
# if(state_modifiers.size() > 0 and debug_state_machine):
|
|
# print("Active Modifiers:")
|
|
# for mods in state_modifiers:
|
|
# print(mods.name)
|
|
|
|
func change_to_known_state(new_state_name: String) -> void:
|
|
if new_state_name.empty() == false:
|
|
if states.has(new_state_name):
|
|
change_state(states[new_state_name])
|
|
else:
|
|
push_warning("Attempt to switch state to unknown: " + new_state_name + get_parent().name)
|
|
change_state(states["default"])
|
|
|
|
# Pass through functions for the Player to call,
|
|
# handling state changes as needed.
|
|
func process_physics(delta: float) -> void:
|
|
change_to_known_state( current_state.process_physics(delta) )
|
|
|
|
func process_input(event: InputEvent) -> void:
|
|
var new_state = current_state.process_input(event)
|
|
if new_state:
|
|
change_state(new_state)
|
|
|
|
func process_frame(delta: float) -> void:
|
|
var new_state = current_state.process_frame(delta)
|
|
if new_state:
|
|
change_state(new_state)
|