2
$\begingroup$

Is there any way to add bone constraint through python api? For example, I have two armatures:

armature1 = scene.objects['armature1']
armature2 = scene.objects['armature2']

Next, I select bone from each of armatures:

selected_bone = armature1.pose.bones["neck"]
target_bone = armature2.pose.bones["neck"]

And now I need to add a bone constraint for selected_bone to copy rotation of target_bone. Does python API have such method?

$\endgroup$
3
$\begingroup$

Here is a quick example adding a copy rotation constraint to the active pose bone (in your case selected_bone), and giving it as a target the pose bone "Bone" from armature object "Armature.001" (target_bone). Notice you use the bone's name for a subtarget.

import bpy
#context & scene for testing
context = bpy.context
scene = context.scene

#active pose bone as example
bone = context.active_pose_bone
bone2 = None
# other armature other bone
arm2 = scene.objects.get("Armature.001")
if arm2 is not None:
    bone2 = arm2.pose.bones.get("Bone")
# give it a copy rotation constraint
if bone is not None:
    crc = bone.constraints.new('COPY_ROTATION')
    #give it a target bone
    crc.target = arm2
    # note subtarget uses name not object.
    crc.subtarget = bone2.name
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.