Skip to content

Instantly share code, notes, and snippets.

@whoiscarlo
Created November 3, 2017 18:57
Show Gist options
  • Save whoiscarlo/bb1ad7d323296ebb1db60034cb74025b to your computer and use it in GitHub Desktop.
Save whoiscarlo/bb1ad7d323296ebb1db60034cb74025b to your computer and use it in GitHub Desktop.
from maya.api import OpenMaya
from maya import cmds
def getDistance(x1, y1, z1, x2, y2, z2):
sq1 = (x1-x2)*(x1-x2)
sq2 = (y1-y2)*(y1-y2)
sq3 = (z1-z2)*(z1-z2)
return math.sqrt(sq1 + sq2 + sq3)
def getClosestVertToObject(obj, surface, distance_max=2):
for each in [obj, surface]:
if not cmds.objExists(each):
raise Exception('%s does not exists'%each)
space = OpenMaya.MSpace.kWorld
## Get Object Position
mSelect = OpenMaya.MSelectionList()
mSelect.add(obj)
obj_dagPath = mSelect.getDagPath(0)
obj_MFnTransform = OpenMaya.MFnTransform(obj_dagPath)
obj_MPoint = obj_MFnTransform.rotatePivot(space)
obj_pos = [round(x, 3) for x in obj_MPoint][:3]
## Get Surface MFnMesh
mSelect = OpenMaya.MSelectionList()
mSelect.add(surface)
surface_dagPath = mSelect.getDagPath(0)
surface_MFnMesh = OpenMaya.MFnMesh(surface_dagPath)
## Get Vertex ids of surface
vertIds = surface_MFnMesh.getVertices()[1]
closest_vert_list = []
for each in vertIds:
vert_pos = surface_MFnMesh.getPoint(each)
vert_pos = [round(x, 3) for x in vert_pos][:3]
## Get distance of objects
distance = getDistance(*obj_pos+ vert_pos)
if distance< distance_max:
closest_vert_list.append(each)
vert_list = []
for ii in closest_vert_list:
node = surface+ '.vtx[%s]'%(ii)
vert_list.append(node)
## Select Vertex
cmds.select(vert_list)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment