Search code examples
mathvectormayapymel

How can I find points at an equal distance between 2 objects?


I'm trying to find points at an equal distance between 2 other points in 3D space. For example, I have 2 cubes in my scene. I want to add 5 (or 3, or 80...) locators at an equal distance between these two spheres with Pymel.

I can easily find the midway point between the spheres like this:

import pymel.core as pm
import pymel.core.datatypes as dt

pos_1, pos_2 = pm.selected()

point_1 = dt.Vector(pos_1.getTranslation())
point_2 = dt.Vector(pos_2.getTranslation())

midway_point = (point_1 + point_2) / 2

However, I can't seem to figure out how to get multiple points on the line between the two spheres.

I tried something like this:

import pymel.core as pm
import pymel.core.datatypes as dt

pos_1, pos_2 = pm.selected()

point_1 = dt.Vector(pos_1.getTranslation())
point_2 = dt.Vector(pos_2.getTranslation())

distance = point_1.distanceTo(point_2)
divided_distance = distance / 5

for i in range (1, 5):
    position = point_1 + (divided_distance * i)
    pm.spaceLocator(position = position, absolute = True)

Which does add 5 locators between the two spheres, but they're not on the line connecting the two points in 3D space.

Can anyone point me in the right direction?


Solution

  • When you calculate the distance between the two points, you're getting a scalar, essentially a single number that is the number of units the points are away from each other. But what you're not getting is the direction from one to the other. That would be a vector. To get the vector, change this line:

    distance = point_1.distanceTo(point_2)
    

    to this:

    difference = point_2 - point_1
    

    Now instead of getting the single unit distance between the two points, you're getting a vector with the distance required for each of the three axes.

    Almost miraculously, all the other code in your script will work if you just replace the variable distance with difference