Programmatically add a frame based animation

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By learis

Hello Im new and I just finished some animations using the visual editor. But now Id like to programmatically recreate the animation. I have a sprite with a spritesheet for its texture. And all I want the animation to do is a walk cycle. So id like to programmatically create an animation and add a track with keyframes at specified times that tell what frame of the spritesheet to use. Is there a tutorial somewhere for this because Im having a hard time understanding the methods and what exactly to put in them.

:bust_in_silhouette: Reply From: MysteryGM

Your mistake was making a spritesheet. Yea, I know: What!?

Godot wants you to create the animations using individual images, because apparently that is better; even when the only advantage is that it is easier.

On Reddit coppolaemilio made a good tutorial: Reddit - Dive into anything

It is aimed at Game maker users, but it shows the basics of how you would use a lot of individual sprites to make a animation.

If you want to use sprite sheets, Because they are better on RAM, render faster, load faster, use less disk space and help keep everything organized. You will need to use a addon for Godot.
Look for Godot “Texture Atlas”.

:bust_in_silhouette: Reply From: learis

I found an example online that helped me accomplish this programmatically.

This specific link focuses on opacity which is a property of texture, but its logic can be used for any properties that can be animated, so I was able to modify it to be used for the frame property. Here’s a snippet of my code that does it. This all takes place within a script for a Sprite. My particular spritesheet had 4 vframes and 3 hframes. And the particular walk animation I wanted to use was on the 6,7, and 8th frames. An important note is to make sure you use the method to set the animation update mode to Discrete, otherwise you get weird things happening for the walk cycle.

func _ready():
self.texture = load("res://TheSpriteSheet.png")
self.vframes = 4
self.hframes = 3

var walkAnimation =
walkAnimation.length = 0.8

var path = String(self.get_path()) + ":frame"
walkAnimation.track_set_path(0, path)
walkAnimation.track_insert_key(0, 0.0, 6)
walkAnimation.track_insert_key(0, 0.2, 7)
walkAnimation.track_insert_key(0, 0.4, 8)
walkAnimation.track_insert_key(0, 0.6, 7)
walkAnimation.value_track_set_update_mode(0, Animation.UPDATE_DISCRETE)
walkAnimation.loop = 1

var aPlayer =
aPlayer.add_animation("walk", walkAnimation)