Advancing AnimatedSprite2D on a timer?

Godot Version

4.1

Question

I’m trying to advance the animation of an AnimatedSprite2D by one frame on a timer. Here’s the code I have:

extends CharacterBody2D

@onready var sprite = $AnimatedSprite2D

func _ready() → void:

attack_timer = Timer.new()
attack_timer.autostart = true
attack_timer.wait_time = 1
attack_timer.timeout.connect(_on_attack)
add_child(attack_timer)

func _on_attack() → void:
sprite.frame += 1
var AnimFinished = sprite.sprite_frames.get_frame_count(sprite.animation)
if sprite.frame >= AnimFinished:
sprite.frame = 0

The animation is not advancing though. Did I miss something?

The reason I’m doing this is because I want the enemy to deal damage on the same timer that the animation advances. I’m sure there are plenty of ways to do this, but I couldn’t find a way to detect an animation frame change in my research. Bonus points if someone knows how to do this.

I wouldn’t do this with an AnimatedSprite2D.
Instead, you should use a normal Sprite2D, and use an AnimationPlayer to manually change the Sprite’s texture each frame you want. This way, you can easily call a function using the AnimationPlayer on any frame you wish.

However, if you are dead set on doing it this way, you can indeed check when a frame changed and check which frame the animation is currently on, and if it matches the frame you need, call your function. AnimatedSprite2D has a signal called frame_changed

1 Like