Advance AnimatedSprite frame manually

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By CesarAugusto
:warning: Old Version Published before Godot 3 was released.

Hello!

It’s possible to advance the animation frame manually? I mean: supose that I have an animation with 4 frames, if I press the Enter button, the animation frame will increase in one step till I reach index 3 and, if I press enter again, the frame will return from beginning, in other words, to frame 0. I thought Godot had a function like AnimatedSprite.next_frame(), but not.

How could I implement this?

:bust_in_silhouette: Reply From: kidscancode

You could do this with set_frame().

You’d first need to use get_sprite_frames().get_frame_count() to know how many frames you have, and then keep track of which frame you’re on, so you can reset back to 0 when you reach the end. The % operator is useful for this.

It would work something like this:

extends AnimatedSprite

var num_frames
var current_frame = 0

func _ready():
    set_process_input(true)
    num_frames = get_sprite_frames().get_frame_count("anim_name")

func _input(event):
    if input.is_action_pressed("ui_select"):
        current_frame = (current_frame + 1) % num_frames
        set_frame(current_frame)

AnimatedSprite reference:

That’s what I was thinking! But if my animation has 4 frames (from 0 to 3) what happens when the variable current_frame is higher than 3? The set_frame return to 0 ?

CesarAugusto | 2017-08-24 22:05

Yes, because (3 + 1) % 4 is 0

kidscancode | 2017-08-24 22:40

Owww I didn’t notice the (current_frame + 1) % num_frames, my bad.

CesarAugusto | 2017-08-24 22:42