Home > Software engineering >  How to change the XFade on a transition node in script?
How to change the XFade on a transition node in script?

Time:02-27

I'm currently learning Godot and my textbook seems to be a bit out of date as it still uses the deprecated AnimationTreePlayer. So I've had to figure out AnimationTree on my own. The exercise for this lesson talks about changing the XFade for the transition node to a random value when the player presses the "up" key but I cannot for the life of me figure out how to do it. I see in the documentation that AnimationNodeTransition has a set_cross_fade_time(value) method but how do I get to it? How do I even access the tranisition node in the script? I've tried things like $AnimationTree/Transition and $AnimationTree["parameters/Transition"] but nothing I've tried works.

My script is currently on the root node and the node tree looks like this:

  • Sprite [script is here]
    • AnimationPlayer
    • AnimationTree

CodePudding user response:

Let us say you have your AnimationTree with the AnimationPlayer set on the anim_player property. And the tree_root of the AnimationTree is an AnimationNodeBlendTree, where - among other nodes - you have an AnimationNodeTransition.


As you are aware, we can get some "paramters" of the AnimationTree, they should appear in the Inspector Panel. And there you should find this one:

$AnimationTree.get("parameters/Transition/current")

Where "Transition" is the name of the node in the AnimationNodeBlendTree. But there isn't a parameter for the xfade_time.


Instead we will get the root of the AnimationTree (in other words, the AnimationNodeBlendTree) like this:

var blend_tree := $AnimationTree.tree_root as AnimationNodeBlendTree

Then we can get the nodes like this:

var blend_tree := $AnimationTree.tree_root as AnimationNodeBlendTree
var node := blend_tree.get("nodes/NodeName/node")

By the way, if you change "/node" to "/position" you get a Vector2 with the position of the node on the editor.

So, let us say we want a node called "Transition", which is our AnimationNodeTransition. We do this:

var blend_tree := $AnimationTree.tree_root as AnimationNodeBlendTree
var transition := blend_tree.get("nodes/Transition/node") as AnimationNodeTransition

And finally we can access xfade_time. Set a random value you said? This should do:

var blend_tree := $AnimationTree.tree_root as AnimationNodeBlendTree
var transition := blend_tree.get("nodes/Transition/node") as AnimationNodeTransition
transition.xfade_time = rand_range(0.0, 120.0)

Or as a one line:

$AnimationTree.tree_root.get("nodes/Transition/node").xfade_time = rand_range(0.0, 120.0)

Be aware that the value of xfade_time is the number of seconds for the transition. So setting 120 give you a two minutes transition.

  • Related