# https://blender.stackexchange.com/questions/82074/python-script-that-sets-target-vertex-group-for-object-constraint
import bpy
def index_of_closest_vertex(location, obj):
verts = obj.data.vertices
choice = 0
wLoc = obj.matrix_world * verts[choice].co
d = (location - wLoc).magnitude
for i in range(1, len(verts)):
vLoc = verts[i].co
wLoc = obj.matrix_world * vLoc
d2 = (location - wLoc).magnitude
#print( [ location, wLoc, choice, d, d2])
if d2<d:
choice = i
d = d2
return choice
def create_per_vertex_vg(obj):
nVerts = len(obj.data.vertices)
for i in range(nVerts):
vgname = "vg %d"%i
vg = obj.vertex_groups.get(vgname)
if vg is None:
vg = obj.vertex_groups.new(vgname)
else:
vg.remove([ j for j in range(nVerts) if j!=i ] )
vg.add([i], 1.0, 'REPLACE')
#
def find_or_create_clc(obj):
for cns in obj.constraints:
if cns.type=="COPY_LOCATION":
return cns
return obj.constraints.new('COPY_LOCATION')
def vg_for_i(obj, vertIdx):
for vg in obj.vertex_groups:
try:
if (vg.weight(vertIdx)>0):
return vg
except:
pass
return None
def set_constraint(src, tgt):
""" put a copy_location constraint on tgt referencing the vertex group for the closest vertex"""
i = index_of_closest_vertex(tgt.location, src)
cns = find_or_create_clc(tgt)
cns.target = src
cns.subtarget = vg_for_i(src, i).name
#
def mission1():
o1 = bpy.data.objects['Cube']
create_per_vertex_vg(o1)
knob = bpy.data.objects['Sphere']
set_constraint(o1, knob)
#
#
#
mission1()
|
Blender python API quick-start
Syntax highlighting by Pygments.