Question
I’m pretty new to Godot and my attack animation is playing the first frame, I tried many things, but it doesn’t work I used the base templet for the movement and added a few things to it the code, the game I’m working on is 2d. here is the code
extends CharacterBody2D @onready var animated_sprite: AnimatedSprite2D = $AnimatedSprite2D
const SPEED = 300.0
const JUMP_VELOCITY = -400.0
func _physics_process(delta: float) → void:
# Add the gravity.
if not is_on_floor():
velocity += get_gravity() * delta
# Handle jump.
if Input.is_action_just_pressed("ui_accept") and is_on_floor():
velocity.y = JUMP_VELOCITY
# Get the input direction and handle the movement/deceleration.
# As good practice, you should replace UI actions with custom gameplay actions.
var direction := Input.get_axis("move_left", "move_right")
if direction:
velocity.x = direction * SPEED
else:
velocity.x = move_toward(velocity.x, 0, SPEED)
move_and_slide()
if direction == 0:
animated_sprite.play("idle")
else:
animated_sprite.play("run")
if direction < 0:
animated_sprite.flip_h = true
if direction > 0:
animated_sprite.flip_h = false
if Input.is_action_just_pressed("attack_action"):
animated_sprite.animation = "attack"
Its only playing the first frame, because in the next frame either “idle” or "run is getting called, which overwrites your old animation.
To fix this you should use a state-machine. There are many tutorials on youtube.
Another quick but ugly solution would be the following:
extends CharacterBody2D
@onready var animated_sprite: AnimatedSprite2D = $AnimatedSprite2D
const SPEED = 300.0
const JUMP_VELOCITY = -400.0
var attacking: bool = false
func _ready() -> void:
animated_sprite.animation_finished.connect(_on_animation_finished)
func _physics_process(delta: float) → void:
# Add the gravity.
if not is_on_floor():
velocity += get_gravity() * delta
# Handle jump.
if Input.is_action_just_pressed("ui_accept") and is_on_floor():
velocity.y = JUMP_VELOCITY
# Get the input direction and handle the movement/deceleration.
# As good practice, you should replace UI actions with custom gameplay actions.
var direction := Input.get_axis("move_left", "move_right")
if direction:
velocity.x = direction * SPEED
else:
velocity.x = move_toward(velocity.x, 0, SPEED)
move_and_slide()
if attacking:
return
if direction == 0:
animated_sprite.play("idle")
else:
animated_sprite.play("run")
if direction < 0:
animated_sprite.flip_h = true
if direction > 0:
animated_sprite.flip_h = false
if Input.is_action_just_pressed("attack_action"):
attacking = true
animated_sprite.animation = "attack"
func _on_animation_finished() -> void:
if animated_sprite.animation == "attack":
attacking = false
Note that you can still jump while attacking, you can stop that by checking if you are currently attacking