Distance-Weighted Constraints

This quick little script takes a group of objects and parents them to the start and end objects with parent weights based on the object’s distance to the two objects. It could really come in handy for handling stuff like feathers that spread out in a way similar to this.

 

import math
import maya.cmds as cmds


# This script akes the object's constraint weights to parent objects relative to its distance to them

def findDistance(objA,objB):
    # 3d distance formula is the square root of (x2-x1)**2 + (y2-y1)**2 + (z2-z1)**2
    pointA = cmds.xform(objA,q=1,t=1,ws=1)
    pointB = cmds.xform(objB,q=1,t=1,ws=1)
    distance = math.sqrt( (pointB[0]-pointA[0])**2 
                        + (pointB[1]-pointA[1])**2
                        + (pointB[2]-pointB[2])**2)
    return distance
    
def average():
    sel = cmds.ls(sl=1,o=1)
    start = sel[0]
    end = sel[len(sel)-1]
    
    totalDist = findDistance(start,end) 
    a = 1
    while a < len(sel)-1:
        cmds.orientConstraint(start,end,sel[a],mo=1)
        cmds.pointConstraint(start,end,sel[a],mo=1)
        objDist = findDistance(sel[a],start)
        W0 = 1 - objDist/totalDist
        W1 = 1 - W0
        cmds.setAttr(sel[a] + "_orientConstraint1." + start + "W0",W0)
        cmds.setAttr(sel[a] + "_orientConstraint1." + end + "W1",W1)
        cmds.setAttr(sel[a] + "_pointConstraint1." + start + "W0",W0)
        cmds.setAttr(sel[a] + "_pointConstraint1." + end + "W1",W1)
        cmds.setAttr(sel[a] + "_pointConstraint1.offsetX",0)
        cmds.setAttr(sel[a] + "_pointConstraint1.offsetY",0)
        cmds.setAttr(sel[a] + "_pointConstraint1.offsetZ",0)
        a += 1
            
average()

Advertisements
Image

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s