You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
60 lines
1.3 KiB
60 lines
1.3 KiB
extends Node2D
|
|
|
|
class_name FSM
|
|
|
|
@export var root : Node
|
|
|
|
var states = ['idle']
|
|
var current_state = null
|
|
var previous_state = null
|
|
var next_state = null
|
|
var state_duration = 0
|
|
|
|
func set_states(new_states):
|
|
self.states = new_states
|
|
|
|
func _ready():
|
|
pass
|
|
|
|
func _physics_process(delta):
|
|
if current_state == null:
|
|
next_state = states[0]
|
|
_transition()
|
|
return
|
|
|
|
if "before_state" in root:
|
|
root.call("before_state", delta)
|
|
|
|
var current_state_method = current_state + "_state"
|
|
if current_state_method in root:
|
|
root.call(current_state_method, delta)
|
|
|
|
if "after_state" in root:
|
|
root.call("after_state", delta)
|
|
|
|
state_duration += delta
|
|
_transition()
|
|
|
|
|
|
func _transition():
|
|
if next_state != null:
|
|
previous_state = current_state
|
|
current_state = next_state
|
|
next_state = null
|
|
print(get_parent().name + " transitioning to " + current_state)
|
|
|
|
if previous_state:
|
|
var on_exit_state_method = "on_exit_" + previous_state + "_state"
|
|
if on_exit_state_method in root:
|
|
root.call(on_exit_state_method)
|
|
|
|
if "on_state_changed" in root:
|
|
root.call("on_state_changed", previous_state, current_state)
|
|
|
|
state_duration = 0
|
|
var on_enter_state_method = "on_enter_" + current_state + "_state"
|
|
if on_enter_state_method in root:
|
|
root.call(on_enter_state_method)
|
|
|
|
func set_next_state(state):
|
|
next_state = state
|
|
|