Add animation keys from code

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

Hey guys!

I’m tying to add animation keys from code but it’s not working. I have a rectangle (Container node) and I want it to move it size to the left, wait the duration time and go back to the original position. I also want that the show and hide animation (slide to the left then to the right) have one second lenght.

The code that I’m using is this one:

func config_animation():
	var anim = $Animation.get_animation("move")
	var pos = $Body.rect_position
	var size = $Body.rect_size
	anim.track_insert_key(0, 0, pos)
	anim.track_insert_key(0, 1, Vector2(pos.x-size.x, pos.y))
	anim.track_insert_key(0, 1+duration, Vector2(pos.x-size.x, pos.y))
	anim.track_insert_key(0, 2+duration, pos) 

The rectangle moves to the left but does not go back to the original position. I did some debugging using for loops to see if the keys times and values were all correct and they were fine.

What am I doing wrong?

Edit: If I only change the key value from code instead of creating the keys, it works.

Is there a reason that you can’t use a Tween?

Eric Ellingson | 2019-02-18 05:37

Totaly forgot about that. I’m not used to Tween, will try it out and say if I managed to do it. Thanks for the tip!

fpicoral | 2019-02-18 05:46

What is the length of your animation? If it ends before 2+duration, those keys won’t get animated.

jandrewlong | 2019-02-19 15:54

:bust_in_silhouette: Reply From: RenenerG

Hello fpicoral,

on the first sight, it looks like a problem, which a Tween could solve.
For example, you can use the method interpolate_property of a Tween to interpolate the value of a property of any node, from a min_value to a max_value, with the indication of a duration.

So it should be possible to manipulate your Container’s property position, similar to the code in the description for Tween’s in the documentation:

var tween = get_node("Tween") tween.interpolate_property($Node2D, "position", Vector2(0, 0), Vector2(100, 100), 1, Tween.TRANS_LINEAR, Tween.EASE_IN_OUT) tween.start()

Just adapt it for your needs.

Hope it helps! :slight_smile: