Problems playing AnimatedSprite2D animations in GDScript

Godot Version

4.4.1

Question

I created a player scene and using AnimatedSprite2D to animate it. I have a lot of sprite sheets and instead of loading them all individually in the editor I’m loading the files using GDScript and adding them to the sprite frames.

Everything seems to work except I’m seeing the entire sprite sheet when I plan an animation.

This is how I load the images

static func get_all_files_recursive(path: String, files: Array[String] = []) -> Array[String]:
    var dir = DirAccess.open(path)
    #var files: Array[String] = []
    
    if dir:
        dir.list_dir_begin()
        var file_name = dir.get_next()
        while file_name != "":
            if dir.current_is_dir():
                get_all_files_recursive(path.path_join(file_name), files)
            else:
                if !file_name.ends_with(".import"):
                    files.append(path.path_join(file_name))
            file_name = dir.get_next()
        dir.list_dir_end()
    #complete.emit.call_deferred(files)#, complete, files
    #emit_signal("files", files)
    return files

Adding the sprite sheets to the AnimatedSprite2D

var frames: SpriteFrames = $AnimatedSprite2D.sprite_frames
    var player_frames: Array[String] = IO.get_all_files_recursive("res://characters/players/spritesheets", [])
    for name: String in player_frames:
        var frame: Texture2D = load(name)
        
        var file_name: String = name.get_basename().get_file()
        #print(file_name)
        #if not frames.has_animation(name.get_file()):
        #$AnimatedSprite2D
        if !frames.has_animation(file_name):
            frames.add_animation(file_name)
            frames.add_frame(file_name, frame)

Playing an animation. Shows this whole sprite sheet not using it as an animation. From what I understand this should work. Why does it show the whole sheet instead of making an animation out of it?

animated_sprite.animation = "WalkForward_Sword_Body_112"
animated_sprite.play()

So when you wrote this code, did you do after manually creating an animation with one of the sprite sheets?

Because it looks like you’re missing the step where each image is loaded as a sprite sheet, and then you create a piece of each for each frame of the animation. Instead, you’re trying to use each sprite sheet and assume the AnimatedSprite2D knows how to cut it up, which it does not.

1 Like

I figured I was probably missing something.

1 Like

How would I handle this in code? I’m searching but so far I’m only finding how to do it in the editor.

Edit

I did find 2D Sprite animation — Godot Engine (3.1) documentation in English and it appears I have to add a Sprite node and chance hFrames and vFrames values. I’ll confirm when I get it working.

1 Like

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