View Full Version : Calculating Distance between two objects?


Zeusbwr
09 September 2007, 05:05 PM
Does anyone have a script, or know how, to calculate the distance between two objects/points in space? Its pretty simple i'd imagine, im just missing a formula or something.

Im in a rush to find it, so i if i find it first i'll post it. Thanks :)

trancor
09 September 2007, 05:23 PM
To find this, use the command mag, it's the magnitude or distance from 0,0,0 to a vector. So if you subtract two vectors and use mag, you'll be able to figure out the distance between two objects ---


vector $obj1=`getAttr pSphere1.translate`;
vector $obj2=`getAttr pSphere2.translate`;
float $mag=mag($obj2-$obj1);
print ("The distance is "+$mag+" units.");

Zeusbwr
09 September 2007, 05:24 PM
Ok, well im still making a UI, so i have yet to test this, but im posting this none the less to save others time.

def CenterToCenter( self, strObjectA, strObjectB ):
self.mc.select( strObjectA, r=True )
WSPosA = self.mc.xform( q=True, ws=True, t=True )
self.mc.select( strObjectB, r=True )
WSPosB = self.mc.xform( q=True, ws=True, t=True )
return self.PositionToPosition( WSPosA[0], WSPosA[1], WSPosA[2], WSPosB[0], WSPosB[1], WSPosB[2] )

def PositionToPosition( self, posAx, posAy, posAz, posBx, posBy, posBz ):
dx = posAx - posBx
dy = posAy - posBy
dz = posAz - posBz
return math.sqrt( dx*dx + dy*dy + dz*dz )
Untested, but the formula is much more plentiful than i had thought :)

Zeusbwr
09 September 2007, 05:25 PM
hehe i was too late, thx :), i'll lookup 'mag' aswell :)

(btw, we were a minute apart from posting :D)

harmless
09 September 2007, 05:26 PM
use the "mag" melscript command which takes a vector
Set each component of the vector to be point1x - point2x, point1y -point2y, point1z -point2z

that's it! easy!

trancor
09 September 2007, 05:28 PM
If you wanted python, shoulda said, hehe. Well, I like seeing the math usage.

As you know you could import your maya.cmds and use mag as well through python just so it's one line instead of like 10

Zeusbwr
09 September 2007, 05:40 PM
If you wanted python, shoulda said, hehe. Well, I like seeing the math usage.

As you know you could import your maya.cmds and use mag as well through python just so it's one line instead of like 10
Wonder which is faster? ( i have no idea, and no idea how to clock them either )

trancor
09 September 2007, 05:46 PM
I'd think mel at that point. To import the cmds and then call up the same command in python as in mel. And knowing mel ....


Using your script probably ends up being faster hah.

CGTalk Moderation
09 September 2007, 05:46 PM
This thread has been automatically closed as it remained inactive for 12 months. If you wish to continue the discussion, please create a new thread in the appropriate forum.


1