首页 > 解决方案 > 在python中删除父约束时如何将定位器保持在父项的中心

问题描述

import maya.cmds as cmds

sel = cmds.ls(sl = True)
cmds.spaceLocator(n = 'driver')
for i in sel:
    cmds.parentConstraint(i, 'driver', n = 'delPs', mo = False)
#until this line, the 'driver' keeps its position at the centre of i
    cmds.delete('delPs')
#after this line, the 'driver' moves to the pivot point of the last item on the selection. 

删除约束节点后,我试图将定位器(驱动程序)保持在选定对象的中心。我能得到一些建议吗?

标签: pythonmaya

解决方案


我不确定是否理解您的问题,但这里有一些解决方案,希望对您有所帮助,我使用数学而不是约束

from __future__ import division
import maya.cmds as cmds

# =========================
#just to illustrate an exemple selection of 10 sphere combined
import random
psph = [cmds.polySphere()[0] for i in range(4)]
for i in psph:
    cmds.setAttr(i+'.t', random.uniform(0.0, 10), random.uniform(0.0, 10), random.uniform(0.0, 10))
# sph_comb = cmds.polyUnite(psph)
cmds.delete(psph , ch=True)
# ===============================

def getCentroid(sel):

    obj = cmds.ls(sel, o=True)
    sel = cmds.polyListComponentConversion(sel, tv=True)
    sel = cmds.ls(sel, flatten=1)

    if len(obj) > 1:
        pos = []
        for s in sel:
            p = cmds.xform(s, q=1, t=1, ws=1)
            pos += p
    else:
        pos = cmds.xform(sel, q=1, t=1, ws=1)
    nb = len(sel)
    myCenter = sum(pos[0::3]) / nb, sum(pos[1::3]) / nb, sum(pos[2::3]) / nb

    return myCenter

# example for each sphere
sel= cmds.ls(psph)
for i in sel:
    loc = cmds.spaceLocator(n = 'driver')[0]
    coord = getCentroid(i)
    cmds.setAttr(loc+'.t', *coord)

# for only one at the center of all sphres
sel= cmds.ls(psph)
coord = getCentroid(sel)
loc = cmds.spaceLocator()[0]
cmds.setAttr(loc+'.t', *coord)

编辑:修复我的函数 getCentroid 的一些代码问题,因为 xform 可以获得多个对象


推荐阅读