GDScript:有限状态机(FSM)的实现

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
"""

发布了261 篇原创文章 · 获赞 134 · 访问量 8万+

猜你喜欢

转载自blog.csdn.net/hello_tute/article/details/103792684