Help with State Machine transitions

Godot Version

4.3

Question

` I have an enemy NPC scorpion that has State machine node with various states as children such as EnemyIdle, EnemyAttack etc. and I’m trying to transition to the EnemyDead when health <= 0.

The enemy health is managed in script attached to the character node. The states I have all extend State so when transferring between states I use Transitioned.emit(self, “#stateNameHere”) but in the health management area I can’t simply put Transitioned as “Transitioned” is not declared in current scope. I’ve just been stuck on how to link the state machine to the main enemy script. Sorry if this doesn’t make a lot of sense I’m on my last brain cell at this point.

StateMachine script:

extends Node

@export var initial_state: State

var current_state : State
var states : Dictionary = {}

func _ready():
for child in get_children():
if child is State:
states[child.name.to_lower()] = child
child.Transitioned.connect(on_child_transition)

if initial_state:
	initial_state.Enter()
	current_state = initial_state			

func _process(delta):
if current_state:
current_state.Update(delta)

func _physics_process(delta):
if current_state:
current_state.Physics_Update(delta)

func on_child_transition(state, new_state_name):
if state != current_state:
return

var new_state = states.get(new_state_name.to_lower())
if !new_state:
	return

if current_state:
	current_state.Exit()

new_state.Enter()

current_state = new_state

Enemy NPC script:

extends CharacterBody2D
class_name Scorpion

var max_health = 36
var health = 36
var state_machine: Node

func _physics_process(delta: float) → void:

if velocity.length() > 0:
	$AnimatedSprite2D.play("IdleWalk") 

if velocity.x > 0:
	$AnimatedSprite2D.flip_h = false
else:
	$AnimatedSprite2D.flip_h = true

move_and_slide()

func _ready() → void:

health = max_health
state_machine = $StateMachine

func _on_hurt_box_area_entered(hitbox: Hitbox):
health -= hitbox.damage
if health <= 0:

	pass

Is there any easy way to transition to the EnemyDead state? Thanks for any help. I’m trying to learn as I go while looking at fundamentals on the side but the time I’m able to learn/practice has large gaps in between so retention has been an issue.

Seems like you could call on_child_transition with your dead state name

if health <= 0:
    state_machine.on_child_transition(state_machine.current_state, "YourDeadStateNodeName")

Make sure to format your pastes properly

1 Like

Thanks a lot, it transitioned now and I also appreciate the formatting info. Now I just need to figure out how to stop animatedsprite2D death animation to stop looping, its not checked to loop but its doing it anyway.

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.