import bpy from random import random from mathutils import Matrix, Quaternion class ArmGraspController: def __init__(self, armature_name): self.arm = bpy.data.objects[armature_name] self.open = False self.finger_grab_bones = ["index_3", "middle_3", "ring_3", "pinky_3"] self.thumb_rot_bone = "thumb_3" def deselect_all_bones(self): for bone in self.arm.pose.bones: # Deselect all selected bones bone.bone.select = False def open_fingers(self): self.grab_movement(0.8) def close_fingers(self): self.grab_movement(-0.8) def move_fingers(self): if self.open: self.open_fingers() else: self.close_fingers() self.open = not self.open def grab_movement(self, angle): # select the 4 base finger bones # Then: # To rotate around local axis (will cause to grab) # Then do the same with thumb, but only around local Z axis! bpy.ops.object.mode_set(mode='OBJECT') bpy.ops.object.select_all(action='DESELECT') # Deselect all objects bpy.context.view_layer.objects.active = self.arm # Make the Armature the active object bpy.ops.object.mode_set(mode='POSE') # Deselect all fingers self.deselect_all_bones() # Rotate fingers for name in self.finger_grab_bones: bone = self.arm.pose.bones.get(name) # Bones need to be selected when adding keyframes, otherwise blender will throw an error: # https://blender.stackexchange.com/questions/1828/what-constitutes-a-context-in-pose-mode bone.bone.select = True # rotate bone.rotation_mode = 'XYZ' bone.rotation_euler.rotate_axis('X', angle) # bpy.ops.transform.rotate(value=angle, orient_axis='X', orient_type='GLOBAL') # Add keyframe bpy.ops.anim.keying_set_active_set(type='Rotation') bpy.ops.anim.keyframe_insert(type='Rotation') # Now rotate the thumb too self.deselect_all_bones() bone = self.arm.pose.bones.get(self.thumb_rot_bone).bone if bone: bone.select = True bpy.ops.transform.rotate(value=angle, orient_axis='Z', orient_type='LOCAL') bpy.ops.anim.keyframe_insert(type='Rotation') ob = bpy.data.objects['Sphere'] frame_number = 0 max_dist = 0.5 #start_location = ob.location.copy() start_location = (1.6766993999481201, 0.3146645724773407, -1.3483989238739014) # Script start controller = ArmGraspController("Armature") for i in range(12): x = random()*max_dist y = random()*max_dist z = random()*max_dist bpy.context.scene.frame_set(frame_number) ob.location = ( start_location[0] + x, start_location[1] + y, start_location[2] + z ) ob.keyframe_insert(data_path='location', index=-1) controller.move_fingers() frame_number += 20