'''
dynamicToTranslateKey.py v1.0
Author: Nate Lang
web: natelang3d.com
Install: Copy + paste this code as a python button on your shelf
USE:
This script averages the vertex positions of an object and then
takes a child object and moves its transforms to that averaged
position. Useful for converting dynamic objects to keyframes.
'''
from maya import cmds
#select dynObj then keyObj
objList = cmds.ls(selection=True)
dynObj = objList[0]
keyObj = objList[1]
#total num of verts on dynObj
totalVtx = cmds.polyEvaluate(dynObj, vertex=True)
#print 'Total Number of Vtx: '+ str(totalVtx)
#get vert position
vtxCounter = 0
vtxPosX = 0
vtxPosY = 0
vtxPosZ = 0
while vtxCounter < totalVtx:
vtxName = dynObj+'.vtx['+str(vtxCounter)+']'
tempVector = cmds.pointPosition(vtxName ,world=True, local=False)
#add x,y,z point positions to list
vtxPosX = vtxPosX + tempVector[0]
vtxPosY = vtxPosY + tempVector[1]
vtxPosZ = vtxPosZ + tempVector[2]
vtxCounter = vtxCounter + 1
#average dynObj vertex positions
finalTransX = vtxPosX/totalVtx
finalTransY = vtxPosY/totalVtx
finalTransZ = vtxPosZ/totalVtx
#move the keyObj to the averaged position
cmds.setAttr(keyObj+'.translateX', finalTransX)
cmds.setAttr(keyObj+'.translateY', finalTransY)
cmds.setAttr(keyObj+'.translateZ', finalTransZ)