I’m making a state machine for my game so i can switch through animations and actions of building, mining, idle, etc. Here is my State Machine code:
class_name StateMachine
extends Node
@export var initial_state : State
var states : Dictionary = {}
var current_state : State
var current_state_name : String
func _ready() -> void:
for child in get_children():
if child is State:
states[child.name.to_lower()] = child
child.transition.connect(transition_to)
else:
push_warning("State machine contains child which is not 'State'")
if initial_state:
initial_state._on_enter()
current_state = current_state
func _process(delta : float) -> void:
if current_state:
current_state.on_enter(delta)
func _physics_process(delta : float) -> void:
if current_state:
current_state._on_physics_process(delta)
current_state._on_next_transitions()
func transition_to(node_state_name: String) -> void:
if node_state_name == current_state.name.to_lower():
return
var new_state = states.get(node_state_name.to_lower())
if !new_state:
return
if current_state:
current_state._on_exit()
new_state._on_enter()
current_state = new_state
current_state_name = current_state_name.to_lower()
print("Current State: ", current_state_name)
Here is my State code:
class_name State
extends Node
@warning_ignore("unused_signal")
signal transition
func _on_process(_delta : float) -> void:
pass
func _on_physics_process(_delta : float) -> void:
pass
func _on_next_transitions() -> void:
pass
func _on_enter() -> void:
pass
func _on_exit() -> void:
pass
and lastly my idle State:
extends State
@export var player: CharacterBody2D
@export var animated_sprite_2d: AnimatedSprite2D
var direction: Vector2
func _on_process(_delta : float) -> void:
pass
func _on_physics_process(_delta : float) -> void:
if Input.is_action_pressed("walk_left"):
direction = Vector2.LEFT
elif Input.is_action_pressed("walk_right"):
direction = Vector2.RIGHT
elif Input.is_action_pressed("walk_up"):
direction = Vector2.UP
elif Input.is_action_pressed("walk_down"):
direction = Vector2.DOWN
else:
direction = Vector2.ZERO
if direction == Vector2.UP:
animated_sprite_2d.play("idle_back")
elif direction == Vector2.DOWN:
animated_sprite_2d.play("idle_front")
elif direction == Vector2.RIGHT:
animated_sprite_2d.play("idle_right")
elif direction == Vector2.LEFT:
animated_sprite_2d.play("idle_left")
else:
animated_sprite_2d.play("idle_front")
print(direction)
func _on_next_transitions() -> void:
pass
func _on_enter() -> void:
pass
func _on_exit() -> void:
pass
With all these my current_state keeps coming up as in the state machine. Please let me know how I can fix this to progress further. Thanks in advance