FSM类
extends Node
class_name FSM
export var default_state:String = ""
var current_state : State = null
var states : Dictionary = {}
func _ready():
var children = get_children()
for c in children:
if c is State:
states[c.name] = c
switch(default_state)
func _process(delta):
if current_state != null and current_state.has_method("update"):
current_state.update(self,delta)
func switch(state_name:String,param = null):
var state:State = null
if states.has(state_name):
state = states[state_name]
else:
return
if state == current_state:
return
if current_state != null and current_state.has_method("exit"):
current_state.exit(self,param)
if state != null and state.has_method("enter"):
state.enter(self,param)
current_state = state
func stop(param = null):
if current_state != null and current_state.has_method("exit"):
current_state.exit(self,param)
current_state = null
State类
GDScript是一种动态类型语言,因此我在State
中只是定义了一种空类型并约定了一下回调方法。并且在FSM
调用方法前要调用 has_method
判断,下面三个回调方法根据需要实现即可
extends Node
class_name State
"""
func enter(fsm :FSM,para = null):
pass
func update(fsm :FSM,delta:float,para = null):
pass
func exit(fsm :FSM,para = null):
pass
"""