0 votes

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?

in Projects by (140 points)

2 Answers

+1 vote
Best answer

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: http://docs.godotengine.org/en/latest/classes/class_animation.html?highlight=TYPE_VALUE#numeric-constants
(You can also look it up in the editor directly).

by (27,166 points)
selected by
0 votes

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.

by (140 points)

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

Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to webmaster@godotengine.org with your username.

Categories