Math: length of a 3D vector in maya

I have a script to determine the distance between two objects, but it’s just creating a “distanceBetween” node, connecting, getAttr(obj.distance) and then deleting it. Seems very inefficient.

Is there a way to extract the distance from a matrix or a vector with math? I’m sure there’s some elegant way to calculate that!

And then how would I code this in python cmds? or with OpenMaya?

you can subtract 1 vector from the other, then get its length. in OpenMaya api there is the MVector type for this, otherwise you could use something like this https://github.com/theodox/vector.

also doing the math manually is pretty simple the subtraction of 2 vectors is just subtract each component from each other to create a new vector. then to get the length of the vector you square each component, add it to the previous then get the square root. `sqrt(x^2 + y^2 + z^2)`

sweet that’s exactly what I needed! Thanks.

Here’s how I wrote it:

``````import maya.cmds as cmds
import maya.api.OpenMaya as om2

def distance(obj1, obj2):
# define vectors
vec1 = om2.MVector(cmds.xform(obj1, q = True, t = True))
vec2 = om2.MVector(cmds.xform(obj2, q = True, t = True))
# subtract them
vec = vec2 - vec1
# calculate vector length
dist = om2.MVector.length(vec)
return dist
``````

FWIW, square roots are comparatively expensive – if you are checking one distance, or even a thousand distances, it’s not a big deal… but if you are checking a hundred thousand it will add up. At that point a common trick is to do the “manhattan distance” , the sum of the differences in X, Y and Z. It won’t be correct but it will be a decent approximation, so you can use it to cut down the number of real `sqrt(x^2 + y^2 + z^2)` checks for speed – you can skip detail checks when the approximate distance is way too big or way too small to bother checking in detail

3 Likes