1

I'm trying to move the selected object pivot to the center of a selection of vertices.

I have gotten to the point where I have the xform defined, but can't seem to move the object (defined as obj) pivot to this point

import maya.cmds as cmds

sel = cmds.ls(sl=True)
print sel
obj = cmds.ls(*sel, o=True)
print obj

selVerts = cmds.ls(sl=True)
tempClstr = cmds.cluster()
pos = cmds.xform(tempClstr[1], q=True, ws=True, rp=True)
loc = cmds.spaceLocator()
cmds.move(pos[0], pos[1], pos[2])
cmds.delete(tempClstr)

piv = cmds.xform (loc[1], piv=True, q=True, ws=True)
print piv
cmds.xform( obj, ws=True, piv=(piv[0], piv[1], piv[2]) ) 

Here's what I've got, any extra eyes that can spot what im missing would be greatly appreciated.

Ricardo Rocha
  • 14,612
  • 20
  • 74
  • 130
Bastart
  • 21
  • 1
  • 4
  • Possible duplicate of [Maya Python - Set object pivot to selection center](http://stackoverflow.com/questions/39902493/maya-python-set-object-pivot-to-selection-center) – Green Cell Oct 24 '16 at 01:36

1 Answers1

1

Your obj needs to be the transform node, but instead it is an array where each element is the same shape.

Try this:

import pymel.core as pm
bigNum = 1.0e+9
sel = pm.ls(sl=True, flatten=True)
min = pm.dt.Point(bigNum,bigNum,bigNum)
max =  pm.dt.Point(-bigNum,-bigNum,-bigNum)

for v in sel:
    p = pm.pointPosition( v )
    if p.x < min.x:
        min.x = p.x
    elif p.x > max.x:
        max.x = p.x
    if p.y < min.y:
        min.y = p.y
    elif p.y > max.y:
        max.y = p.y     
    if p.z < min.z:
        min.z = p.z
    elif p.z > max.z:
        max.z = p.z    

center = (min+max)*0.5

obj =  pm.listRelatives(pm.listRelatives(sel[0], p=True), p=True)
pm.xform (obj, piv=(center.x, center.y, center.z) , ws=True)
pm.spaceLocator(p=center)

pm.select(obj)

The flatten flag of ls will make sure every vertex has an entry in the result array. Vertices with adjacent indices will not be grouped.

Rather than make a temporary cluster, it iterates to find the world space bounding box, and then calculates its center.

The call to listRelatives nested in another listRelatives gets the transform node associated with the first vertex. (It assumes all selected vertices are in the same mesh).

Julian Mann
  • 6,256
  • 5
  • 31
  • 43