I am starting with the animation nodes and I am trying to replace as many nodes as possible with Python code; it is especially nice for the math. However, now I am stuck with the looping. Is it possible to replace the Loop Input and its generators with Python code plus other nodes? thanks
-
$\begingroup$ Hello, are you talking about "Expression" nodes (where you can only write one single line of code) or "Script" nodes, where you can write as many lines as you want in a text block ? $\endgroup$– GorgiousAug 1, 2020 at 10:43
-
$\begingroup$ I understand that in Expression nodes one can put only one line of code so looping would be difficult but in scripting nodes it should be possible. I am just not sure how to reproduce the Loop input and generators in the script $\endgroup$– kwicherAug 1, 2020 at 12:18
1 Answer
You just have to know how to access input variables and how to output variables in the script. Otherwise it's just common python operations. Mainly you will have to use for
loops.
Let's see how to emulate a loop with a python script, for example to output a list of the location of each object in a given collection.
Here in my collection I have 3 objects.
And here the simple setup to output their locations using a loop node :
Now, to do the same with a script node. Add your script node, add a text block with the + icon. Add a new input of type "Collection", I renamed it "col". Add a new output of type "Vector list", I renamed it "positions".
In a text editor, find your new script textblock and open it. Write a few lines to do the job.
positions = []
for obj in col.objects:
positions.append(obj.location)
Or with list comprehension
positions = [obj.location for obj in col.objects]
Note that col
hasn't been defined in this text block : AN gives it context since you told the script node that a variable named col
will be available, as a collection type.
Similarly, you have to define the variable positions
and at the end of the execution of the script, AN will automatically gather its value.
/!\ col
and positions
are case sensitive. They have to match the variable names you wrote in the script node.
Add an invoke node set to your script, execute the AN tree and voilà :