I have written some code that calculates the world space coordinate I want to move the bone to but i am having trouble figuring out how to get that back into the bones coordinates.
from bpy import context, data
from mathutils import Vector
def test_empty(matrix, name):
# view matrix by applying it to an object
obj_empty = data.objects.new(name, None)
context.scene.objects.link(obj_empty)
obj_empty.matrix_world = matrix
armature = data.objects["Armature"]
pbones = armature.pose.bones
root = pbones["root"]
hips = pbones["hips"]
test = pbones["test"]
# calculate root
root_matrix = armature.matrix_world * root.matrix
test_empty(root_matrix, "Root")
# calculate hips
hips_matrix = armature.matrix_world * hips.matrix
test_empty(hips_matrix, "Hips")
# calculate bone
test_matrix = armature.matrix_world * test.matrix
test_empty(test_matrix, "Test")
# get offset of hips from root bone
offset = root_matrix.translation - hips_matrix.translation
print(offset)
# calculate new location in local space
new_position = test_matrix.translation + Vector((0,offset.y,0))
obj_empty = data.objects.new("TEST", None)
context.scene.objects.link(obj_empty)
obj_empty.location = new_position
# obviously something wrong here
new_position = armature.matrix_world.inverted() * new_position
# move bone to new location
test.location = new_position