Blender Recipes: construct a stick figure in blender bpy, then animate it waving it’s hand

#construct a stick figure in blender bpy, then animate it waving it's hand
import bpy
import math

# Clear the existing scene
for obj in bpy.data.objects:
    bpy.data.objects.remove(obj)

# Create a new collection
collection = bpy.data.collections.new("Stick Figure Collection")
bpy.context.scene.collection.children.link(collection)

# Create the stick figure armature
arm = bpy.data.armatures.new("Stick Figure")
obj = bpy.data.objects.new("Stick Figure Object", arm)
collection.objects.link(obj)
bpy.context.scene.collection.objects.link(obj)

# Create the bone structure
bpy.context.view_layer.objects.active = obj
bpy.ops.object.mode_set(mode='EDIT')
bone_head = arm.edit_bones.new('Head')
bone_body = arm.edit_bones.new('Body')
bone_arm_l = arm.edit_bones.new('Arm.L')
bone_arm_r = arm.edit_bones.new('Arm.R')
bone_leg_l = arm.edit_bones.new('Leg.L')
bone_leg_r = arm.edit_bones.new('Leg.R')

# Set bone relationships
bone_body.parent = bone_head
bone_arm_l.parent = bone_body
bone_arm_r.parent = bone_body
bone_leg_l.parent = bone_body
bone_leg_r.parent = bone_body

# Set bone positions and rotations
bone_head.head = (0, 0, 0)
bone_head.tail = (0, 0, 1)
bone_body.head = (0, 0, 1)
bone_body.tail = (0, 0, 3)
bone_arm_l.head = (0, 0, 2)
bone_arm_l.tail = (-1, 0, 2)
bone_arm_r.head = (0, 0, 2)
bone_arm_r.tail = (1, 0, 2)
bone_leg_l.head = (0, 0, 2)
bone_leg_l.tail = (-0.5, 0, 1)
bone_leg_r.head = (0, 0, 2)
bone_leg_r.tail = (0.5, 0, 1)

bpy.ops.object.mode_set(mode='OBJECT')

# Animate the arm waving
arm_r = obj.pose.bones['Arm.R']
frames = 30
for i in range(frames):
    arm_r.rotation_quaternion = (0, 0, math.sin(i * 2 * math.pi / frames), math.cos(i * 2 * math.pi / frames))
    arm_r.keyframe_insert('rotation_quaternion', frame=i+1)

Leave a Reply