+1 tag for Google+

Tuesday, 25 November 2014

Distance Between 2 Positions in 3D Space

The ability to find the distance between 2 points in 3D space is a really important function I need to use time and again.

I found this website that is really helpful with clear explanations on the use of the formula.

http://darkvertex.com/wp/2010/06/05/python-distance-between-2-vectors/

From the webpage I learnt the formula for the distance d between points A (expressed as Ax, Ay, Az) and B (expressed as Bx, By, Bz), would be expressed as such:

d = √  Ax-Bx2 + Ay-By2 + Az-Bz2  

I was going to use the distance function on an expression in Maya, so I had to write it with MEL commands:

vector $a = `xform -q -ws -a -rp "objA"`;
vector $b = `xform -q -ws -a -rp "objB"`;
// doing the additions and squaring first
$myDist = `pow ($a.x-$b.x) 2` + `pow ($a.y-$b.y) 2` + `pow ($a.z-$b.z) 2`; 
// applying the square root
$myDist = `sqrt $myDist`; 

I hope you it helps if you are looking for the same information.

Additional notes:
I am writing this a few days after my post because I found a more efficient way to represent the formula.

Instead of using the back ticks "`" for the pow and sqrt, I found that in Maya expressions we can use the equivalent of these commands. They are pow( ) and sqrt( ).

So the shortened single-line expression would be:
$myDist = sqrt(pow(($a.x-$b.x), 2) + pow(($a.y-$b.y),2) + pow(($a.z-$b.z),2))

1 comment:

  1. Assuming Maya has a built-in function to compute the length of a vector, you can write an even shorter line:
    $myDist = length($a - $b);
    We can write it this way in MaxScript :p

    ReplyDelete