简体   繁体   中英

(Blender) (Python)How can I animate the factor value in the mix node with Python code?

What I want is a way to handle the 'factor' value in the mixRGB node like a normal object, like for example a cube, so with fcurves, fmodifiers and so on. All this via Python code made in the Text Editor

The first step is to find the mix node you want. Within a material you can access each node by name, while the first mixRGB node is named 'Mix', following mix nodes will have a numerical extension added to the name. The name may also be changed manually by the user (or python script). By showing the properties region (press N ) you can see the name of the active node in the node properties.

节点属性

To adjust the fac value you alter the default_value of the fac input. To keyframe the mix factor you tell the fac input to insert a keyframe with a data_path of default_value

import bpy
cur_frame = bpy.context.scene.frame_current
mat_nodes = bpy.data.materials['Material'].node_tree.nodes
mix_factor = mat_nodes['Mix.002'].inputs['Fac']

mix_factor.default_value = 0.5
mix_factor.keyframe_insert('default_value', frame=cur_frame)

Of course you may specify any frame number for the keyframe not just the current frame.

If you have many mix nodes, you can loop over the nodes and add each mix shader to a list

mix_nodes = [n for n in mat_nodes if n.type == 'MIX_RGB']

You can then loop over them and keyframe as desired.

for m in mix_nodes:
    m.inputs['Fac'].default_value = 0.5
    m.inputs['Fac'].keyframe_insert('default_value', frame=cur_frame)

Finding the fcurves after adding them is awkward for nodes. While you tell the input socket to insert a keyframe, the fcurve is stored in the node_tree so after keyframe_insert() you would use

bpy.data.materials['Material'].node_tree.animation_data.action.fcurves.find()

Knowing the data path you want to search for can be tricky, as the data path for the Fac input of node Mix.002 will be nodes["Mix.002"].inputs[0].default_value

If you want to find an fcurve after adding it to adjust values or add modifiers you will most likely find it easier to keep a list of them as you add the keyframes. After keyframe_insert() the new fcurve should be at

material.node_tree.animation_data.action.fcurves[-1]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM