programmatically create AnimationPlayer animation, with a property track and a frame property

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

I’m trying to programmatically create AnimationPlayer animation, with a property track and a frame property. My animation has 4 sprites, and the Animation looping is 2.7 seconds. My code is below, but it is not working.

var animPlayer = AnimationPlayer.new()
add_child(animPlayer)

var lefty = Animation.new()
animPlayer.add_animation( "left", lefty)

lefty.add_track(0)
lefty.length = 2.7

var path = String(self.get_path())
print(path)
lefty.track_set_path(0, path)


lefty.track_insert_key(0, 0.0, 12)
lefty.track_insert_key(0, 0.9, 13)
lefty.track_insert_key(0, 1.8, 14)
lefty.track_insert_key(0, 2.7, 15)

Any help is appreciated. Thanks!

:bust_in_silhouette: Reply From: njamster

The path needs to contain the property you want to animate as well:

var path = String(self.get_path()) + ":frame"

adding + “:frame” to my path variable doesn’t work

Ben Nicholl | 2020-05-22 13:13

Why not? Does it throw an error or warning? Of course the object the path refers to needs to have a property called frame - from the code you posted that’s not entirely clear, but I was under the assumption that it extends an AnimatedSprite.

njamster | 2020-05-22 14:12

This code is inside of a sprite, not an animated sprite. Normally if I use the AnimationPlayer node, I click on “add track”, which then allows me to select property track, then the node I will be animating, in this case a sprite, and then lastly, the property type, which is a frame.

Ben Nicholl | 2020-05-22 14:24

I cannot reproduce your issue. This is my code:

extends Sprite

func _ready():
    var animPlayer = AnimationPlayer.new()
    add_child(animPlayer)
    
    var lefty = Animation.new()
    animPlayer.add_animation("left", lefty)
    
    lefty.add_track(0)
    lefty.length = 2.7
    
    var path = String(self.get_path()) + ":frame"
    lefty.track_set_path(0, path)
    
    lefty.track_insert_key(0, 0.0, 1)
    lefty.track_insert_key(0, 0.9, 3)
    lefty.track_insert_key(0, 1.8, 5)
    lefty.track_insert_key(0, 2.7, 7)
    
    animPlayer.play("left")

I used this spritesheet and set the Sprite’s hframes-property to 8.

njamster | 2020-05-22 14:36

And your sprite is actually walking? My sprite doesn’t move.

Ben Nicholl | 2020-05-22 14:43

And your sprite is actually walking?

Yes. Walking in place that is. The frames are updated.

My sprite doesn’t move.

With my code and the spritesheet I linked as well? No idea then…
Can you provide an example project?

njamster | 2020-05-22 14:55

:bust_in_silhouette: Reply From: VipinArl

Not sure you are still interested, and got a result.
But which node has your code?

You should get the path of the sprite.