0
$\begingroup$

I'm trying to snap the head of a bone to the cursor position using the script below, but it's not working as shown in the screenshot.

import bpy

C = bpy.context
obj = bpy.data.objects['Armature']
obj.select = True
C.scene.objects.active = obj
bpy.ops.object.mode_set(mode='EDIT')

bone = obj.data.edit_bones['Bone']
C.area.type = 'VIEW_3D'
bpy.ops.object.mode_set(mode='OBJECT')
bpy.ops.object.select_all(action='DESELECT')
bpy.data.objects['Empty'].select = True
C.scene.objects.active = bpy.data.objects['Empty']
bpy.ops.view3d.snap_cursor_to_selected() 
C.area.type = 'TEXT_EDITOR'
bpy.ops.object.select_all(action='DESELECT')
obj.select = True
C.scene.objects.active = obj
bpy.ops.object.mode_set(mode='EDIT')
bpy.ops.armature.select_all(action='DESELECT')
bone.select_head = True
C.area.type = 'VIEW_3D' 
bpy.ops.view3d.snap_selected_to_cursor(use_offset=False)
C.area.type = 'TEXT_EDITOR'

enter image description here

$\endgroup$
1
  • $\begingroup$ Do you really want it to snap to the empty, and your're just using the cursor to do it? $\endgroup$
    – cmomoney
    Feb 18, 2017 at 15:58

1 Answer 1

1
$\begingroup$

I don't know exactly why your code isn't working, but I assume the end result that you want is the bone head snapping to the empty. The "friendly", non-ops way to do this would be to put it in an operator:

import bpy

def main(context):    
    arm = bpy.data.objects['Armature']
    empty = bpy.data.objects['Empty']
    context.scene.objects.active = arm
    #do snapping here
    bpy.ops.object.mode_set(mode='EDIT')
    bone = arm.data.edit_bones['Bone']
    bone.head.xyz = empty.location
    bpy.ops.object.mode_set(mode='OBJECT')   


class SimpleOperator(bpy.types.Operator):
    """Tooltip"""
    bl_idname = "object.simple_operator"
    bl_label = "Simple Object Operator"

    @classmethod
    def poll(cls, context):
        return context.active_object is not None

    def execute(self, context):
        main(context)
        return {'FINISHED'}


def register():
    bpy.utils.register_module(__name__)


def unregister():
    bpy.utils.unregister_module(__name__)

if __name__ == "__main__":
    register()
$\endgroup$
2
  • $\begingroup$ how using an operator will solve the problem? $\endgroup$
    – Tak
    Feb 20, 2017 at 10:27
  • $\begingroup$ Using an operator isn't what solves the problem, although it probably eliminates any context related issues. $\endgroup$
    – cmomoney
    Feb 20, 2017 at 15:19

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .