State Machine Help

Godot Version

4.3

Question

` Hey all! Ive been battling state machines lately, not really understanding it. My goal is to get the animation of “jump” to play when I jump while moving but I cant seem to figure it out. I followed several tutorials but I don’t think I comprehend what I need to do to get it to work. Any guidance will be much appreciated!

class_name Player
extends CharacterBody2D

@onready var player_anim = $AnimatedSprite2D

@export var player_speed: float = 100.0
@export var player_gravity: float = 125.0 #what brings player down
@export var player_jump: float = -75.0

#var play_idle = player_anim.play(“idle”)
#var play_walk = player_anim.play(“walk”)
#var play_jump = player_anim.play(“jump”)

enum States {IDLE, WALKING, JUMPING}
var state: States = States.IDLE

@onready var parent = get_parent()

func _physics_process(delta):
velocity.y += player_gravity * delta
jump_input()
move_input()
move_and_slide()

func move_input():
var player_input = 0

if Input.is_action_pressed(“left”):
player_input = -1
player_anim.play(“walk”)
player_anim.flip_h = true
elif Input.is_action_pressed(“right”):
player_input = 1
player_anim.play(“walk”)
player_anim.flip_h = false
else:
player_input = 0
player_anim.play(“idle”)

velocity.x = player_speed * player_input

func jump_input():
if is_on_floor() and Input.is_action_just_pressed(“jump”):
velocity.y = player_jump
if !is_on_floor():
player_anim.play(“jump”)

`

A simple way is use a match statement

match state:
     States.IDLE: idle()
     States.WALKING: walking()

func idle():
      if Input.is_action_pressed(“left”):
          state = States.WALKING
1 Like

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