ft (Wip): FSM behaviour prey

This commit is contained in:
2026-01-23 10:48:14 +01:00
parent 0b9b1e75d4
commit c11afd9ddd
24 changed files with 154 additions and 54 deletions

View File

@@ -1,6 +1,10 @@
extends NPC2D
class_name AbstractPrey2D
enum States {IDLE, FORAGING, FLEEING}
var state = States.IDLE
# Called when the node enters the scene tree for the first time.
func _ready() -> void:
pass # Replace with function body.

View File

@@ -1,11 +1,10 @@
extends Node
class_name SpawnManager2D
#var scene = preload("res://molecular/nucleotide_prey.tscn")
@export var scene: PackedScene
@export var minCount = 1
@export var maxCount = 2
@export var spawnRange: Rect2
@export var spawnRange: Rect2 = Rect2(0, 0, 0, 0)
var _currentCount = 0

View File

@@ -0,0 +1,24 @@
class_name State extends Node
# Emits on state completion
signal finished(next_state_path: String, data: Dictionary)
# Called by StateMachine on unhandled input
func handle_input(_event: InputEvent) -> void:
pass
# Main update loop
func update(_delta: float) -> void:
pass
# Physics update loop
func physics_update(_delta: float) -> void:
pass
# Called by StateMachine on state change. Data contains arbitrary data to initialize state.
func enter(previous_state_path: String, data := {}) -> void:
pass
# Called by StateMachine before state change. Should be used for cleanup.
func exit() -> void:
pass

View File

@@ -0,0 +1 @@
uid://co2xp7gauamql

View File

@@ -0,0 +1,39 @@
class_name StateMachine extends Node
@export var initial_state: State = null
# use first child as 'active' state
@onready var state: State = (func get_initial_state() -> State:
return initial_state if initial_state != null else get_child(0)
).call()
# Connect states on ready, then wait.
func _ready() -> void:
for node: State in find_children("*", "State"):
node.finished.connect(_transition_to_next_state)
await owner.ready
state.enter("")
# pass unhandled input to state.
func _unhandled_input(event: InputEvent) -> void:
state.handle_input(event)
# Pass process tick to state.
func _process(delta: float) -> void:
state.update(delta)
# Pass physics tick to state.
func _physics_process(delta: float) -> void:
state.physics_update(delta)
# Transition to next state
func _transition_to_next_state(target_path: String, data: Dictionary = {}) -> void:
if not has_node(target_path):
printerr(owner.name + ": Trying to transition to state " + target_path + ", which does not exist.")
return
var previous_state_path := state.name
state.exit()
state = get_node(target_path)
state.enter(previous_state_path, data)

View File

@@ -0,0 +1 @@
uid://ck7k8ht54snsy