Having trouble creating keyframe animations in code

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

I’m trying to animate an object using keyframes programmatically, but I’m having trouble. Here is a sample that I think should work, but doesn’t:

# I want to animate a sprite added via code, so let's add the sprite.

var sprite = Sprite.new()
sprite.set_texture(sprite_scene) # defined earlier
sprite.set_pos(Vector2(600, 300))
sprite.set_name("TestSprite") # Will be needed for the track path later
add_child(sprite)

# Now that the sprite is added, I try to animate it

var animation = Animation.new()
animation.set_length(1)

# The animation is to move the sprite to the right for 1 second

animation.add_track(TYPE_VECTOR2)
animation.track_set_path(0, "TestSprite:transform/pos")
animation.track_insert_key(0, 0, Vector2(600, 300))
animation.track_insert_key(0, 1, Vector2(800, 300))

# Now that I created the animation, I add it to my AnimationPlayer
# and play the animation. However, the animation does not play.

animation_player.add_animation("Test", animation)
animation_player.play("Test")

What seems to be wrong with this method?

:bust_in_silhouette: Reply From: Beamer159

I found my problem. For the following line:

animation.add_track(TYPE_VECTOR2)

Don’t use TYPE_VECTOR2. This is equal to 5. The only value that seems to work for this parameter is 0. Even though the variable being altered is a Vector2 (position), only 0 seems to work.

More accurately, values 0, 1, and 2 work for this parameter. See Zylann’s answer.

Beamer159 | 2016-09-15 20:39

:bust_in_silhouette: Reply From: Zylann

TYPE_VECTOR2 is a variable type, not an animation track type.
You should use Animation.TYPE_VALUE instead (which is luckily equal to 0).

Whenever you encounter a situation where a function expects a type as an int, you should check the documentation of the class for constants, because that’s where the expected values are: Animation — Godot Engine (latest) documentation in English
(You can also look it up in the editor directly).