Home > Net >  How to change key frame values in GDScript (Godot)?
How to change key frame values in GDScript (Godot)?

Time:10-19

I am trying to play an animation when a scene is instanced. It is a simple animation that translates y from -5 to 5. The animation plays but it plays at x = 0 and z = 0. I understand this is because the translation values for the respective co-ordinates in the animation are set to 0. I have a spatial node on my player scene that can grab transform info and pass it on to my animated scene, but I do not know how to dynamically change the x and z values of the key frames in script.

CodePudding user response:

This answer contains three solutions to the problem...


Target a sub-property

If I understand correctly you want to animate only the y coordinate, and leave the other coordinates unchanged. That is, you don't want to animate the translation vector. You want to animate the y or the translation, a sub-property. This is possible out of the box, but the UI won't offer it to you.

Start by creating a track from the animation editor. You click on "Add Track", select "Property Track", and then on the object you want, and select translation. Now, while the track is empty (no key frame inserted yet), modify the track name to :y at the end.

The track would have been create with a name such as SpatialNodeName:translation, you are going to change it to SpatialNodeName:translation:y.

Afterwards, when you add key frames, they will be for translation.y. Note: doing SpatialNodeName:transform:origin:y or even SpatialNodeName:global_transform:origin:y also works. Similarly, you can imagine how do it for only rotation or scaling, and so on.


Create custom properties and animate them

I'll also mention that another option is using a Tween node (which are easier to create from code).

And also that both Tween and AnimationPlayer can animate any property. Thus, if you need to animate something that is not available, consider adding a property (see setget).

For example:

export var y:float setget set_y, get_y

func set_y(new_value:float) -> void:
    transform.origin.y = new_value

func get_y() -> float:
    return transform.origin.y

Then you can add a track for the custom property, and animate it like any other.

By the way, also notice the AnimationPlayer can also have "Call Method" tracks.


Modify the animation

Manipulating an animation from code is also possible. I've seen an example elsewhere. You can call get_animation on the AnimationPlayer to get the animation. Then on the returned animation you can call track_get_key_value and track_set_key_value. However, this rarely what you want to do in practice (unless you are making a Godot addon that creates or modifies animations or something like that).

  • Related