import maya.cmds as cmds
import pymel.core as pm
selection = cmds.ls(sl=True)
print selection
object_locator_list = []
# create sets to select the controls and locators later
ctrl_set = cmds.sets(empty=True, name='baked_worldspace_ctrl_set')
loc_set = cmds.sets(empty=True, name='baked_worldspace_loc_set')
for obj in selection:
# get objects xform in world space
obj_xform = pm.xform(obj, q=True, matrix=True, worldSpace=True)
# create a locator
loc = pm.spaceLocator(name=('|' + obj + '_locator'))
print loc
# snap the locator to the object
pm.xform(loc, matrix=obj_xform, worldSpace=True)
# put the object and its locator into a list
object_locator_list.append((obj, loc))
# put the obj and the locator into their respective sets
cmds.sets(obj, addElement=ctrl_set)
cmds.sets(loc.name(), addElement=loc_set)
# store the time range start/end
range_min = int(pm.playbackOptions(q=True, min=True))
range_max = int(pm.playbackOptions(q=True, max=True))
# store current time
init_time = pm.currentTime(q=True)
# get the current autokey setting to restore later
auto_key_state = pm.autoKeyframe(q=True, state=True)
# turn off auto key for now
pm.autoKeyframe(state=False)
# go through the time range, keying each locator to match the objects
for t in range(range_min, range_max+1):
pm.currentTime(t)
for(target_obj, loc) in object_locator_list:
target_xform = pm.xform(target_obj, q=True, matrix=True, worldSpace=True)
pm.xform(loc, matrix=target_xform, worldSpace=True)
pm.setKeyframe(loc, attribute=['t','r','s'], respectKeyable=True)
pm.currentTime(init_time)
pm.select(selection)
pm.autoKeyframe(state=auto_key_state)