Created
February 8, 2024 10:40
-
-
Save BigRoy/bcc294fb80e92756aa32b355ed204f98 to your computer and use it in GitHub Desktop.
Maya: Connect Objects translation to param u on NurbsCurve via pointOnCurveInfo node.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
"""Connect objects (transforms) to a nurbsCurve by pointOnCurve node. | |
Select the objects, then select the nurbsCurve last. | |
Run the script. | |
Voila. | |
Updated version of: https://polycount.com/discussion/161754/eye-rig-script-problem | |
""" | |
from maya import cmds | |
import maya.api.OpenMaya as om2 | |
def get_dag_path(node_name): | |
"""Return maya.api.OpenMaya.MDagPath from node name. | |
Args: | |
node_name (str): Maya dag node name. | |
Returns: | |
om2.MDagPath: Dag path for the node. | |
""" | |
sel = om2.MSelectionList() | |
sel.add(node_name) | |
return sel.getDagPath(0) | |
def get_curve_u_param(pos, crv, tolerance=0.001): | |
"""Return closest U param on the nurbs curve. | |
Args: | |
pos (list): Vector of position. | |
curve (str): Name of the curve shape node. | |
Returns: | |
float: U Param. | |
""" | |
point = om2.MPoint(pos) | |
dag = get_dag_path(crv) | |
dag.extendToShape() # make sure to use the shape of the curve | |
fn_curve = om2.MFnNurbsCurve(dag) | |
if fn_curve.isPointOnCurve(point): | |
return fn_curve.getParamAtPoint(point, tolerance, om2.MSpace.kObject) | |
else: | |
point, param = fn_curve.closestPoint(point, | |
tolerance=tolerance, | |
space=om2.MSpace.kObject) | |
return fn_curve.getParamAtPoint(point, tolerance, om2.MSpace.kObject) | |
sel = cmds.ls(selection=True, long=True) | |
if len(sel) < 2: | |
raise RuntimeError("Select objects first and the nurbsCurve last. You must select at least two objects.") | |
# Last object in selection will be used as curve | |
crv = sel.pop() | |
for node in sel: | |
pos = cmds.xform(node, query=True, worldSpace=True, translation=True) | |
u = get_curve_u_param(pos, crv) | |
name = node.rsplit("|", 1)[-1].replace("_LOC", "_PCI") | |
pci = cmds.createNode("pointOnCurveInfo", name=name) | |
cmds.connectAttr(crv + ".worldSpace", pci + ".inputCurve") | |
cmds.setAttr(pci + ".parameter", u) | |
cmds.connectAttr(pci + ".position", node + ".translate") | |
print("Connected objects to curve '{}':\n -{}".format(crv, "\n -".join(sel))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment