Godot Version
v4.3.stable.official
Question
I’m using a state machine and my attack state only holds for the first frame of the animation and then returns to the previous state. Here is my code for reference.
extends CharacterBody2D
@onready var animated_sprite: AnimatedSprite2D = $AnimatedSprite2D
const GRAVITY = 1000
const SPEED = 300
var current_state
var enraged = true
enum State {Holster , Attack , HostileIdle , HostileRun , PassiveIdle , PassiveRun , Wield}
func _ready():
current_state = State.PassiveIdle
func _physics_process(delta):
hostile_state(delta)
passive_idle(delta)
passive_running(delta)
hostile_idle(delta)
hostile_running(delta)
hostile_attack(delta)
move_and_slide()
animations()
print ("State: ", State.keys()[current_state])
func hostile_state(delta):
if Input.is_action_just_pressed(“hostile”) and enraged:
enraged = false
elif Input.is_action_just_pressed(“hostile”) and !enraged:
enraged = true
func passive_idle(delta):
if is_on_floor and !enraged:
current_state = State.PassiveIdle
func hostile_idle(delta):
if is_on_floor and enraged:
current_state = State.HostileIdle
func passive_running(delta):
var direction = Input.get_axis(“move_left”, “move_right”)
if direction:
velocity.x = direction * SPEED * delta
else:
move_toward(velocity.x, 0, SPEED)
if direction != 0:
current_state = State.PassiveRun
animated_sprite.flip_h = false if direction > 0 else true
func hostile_running(delta):
var direction = Input.get_axis(“move_left”, “move_right”)
if direction:
velocity.x = direction * SPEED * delta
else:
move_toward(velocity.x, 0, SPEED)
if direction != 0 and enraged:
current_state = State.HostileRun
animated_sprite.flip_h = false if direction > 0 else true
func hostile_attack(delta):
if enraged and Input.is_action_just_pressed(“attack”):
current_state = State.Attack
func animations():
if current_state == State.PassiveIdle:
animated_sprite.play(“passive_idle”)
elif current_state == State.PassiveRun:
animated_sprite.play(“passive_running”)
elif current_state == State.HostileIdle:
animated_sprite.play(“hostile_idle”)
elif current_state == State.HostileRun:
animated_sprite.play(“hostile_running”)
elif current_state == State.Attack:
animated_sprite.play(“hostile_attack”)