Calculating distances in Blender with Python

In this super quick tip we’ll see how to cal­cu­late the dis­tance between two points. The for­mu­la for Euclidean dis­tance in 3D is the following:

Euclidean formula to calculating distances in 3D

There’s at least three ways to do this in Blender.

The classic way

import math

def distance(point1, point2) -> float:
    """Calculate distance between two points in 3D."""

    return math.sqrt((point2[0] - point1[0]) ** 2 +
                     (point2[1] - point1[1]) ** 2 +
                     (point2[2] - point1[2]) ** 2)

The ben­e­fit of this snip­pet is that it will always be avail­able. It does­n’t depend on a spe­cif­ic Python ver­sion or Blender mod­ules. The down­side is low­er per­for­mance and hav­ing more code.

Using Blender’s Vectors

from mathutils import Vector

def distance_vec(point1: Vector, point2: Vector) -> float:
    """Calculate distance between two points."""

    return (point2 - point1).length

Blender comes with a very con­ve­nient class called Vector. I could write for hours how much I like this class, but let’s stick to distances.

We can eas­i­ly find the dis­tance between two vec­tors by sub­tract­ing them, and then check­ing the length prop­er­ty of the result­ing vec­tor. All blender coor­di­nates are vec­tors. But if you need to make one you can just pass a tuple or list of num­bers to Vector().

Not only is this short­er, but it’s also faster since it’s run­ning on C inter­nal­ly. On top of that, you can make vec­tors of any dimen­sion whether it’s 2D or 26D (for those of you work­ing with string the­o­ry in Blender).

The new functions in Python 3.8

import math

math.dist(point1, point2)

# The hypot way was also updated!
math.hypot(p2.x - p1.x, p2.y - p1.y, p2.z - p1.z)

Python 3.8 comes with a brand new math.dist func­tion that can cal­cu­late dis­tances for iter­ables of any dimen­sion. You can also drop Vectors here, as well as the usu­al Lists and Tuples. This way will prob­a­bly become the stan­dard Python Way™ and you’ll find it in libraries and such. It’s also use­ful to have if you are mix­ing dif­fer­ent kinds of objects since it will take any­thing that can be iterated.

If you want to feel smart, the old Pythagorean Theorem method has also been updat­ed. The hypot() func­tion used to take only 2 coor­di­nates, but now it can take any num­ber of them. There’s no rea­son to do this any­more really.

Python 3.8 will find its way to Blender in 2.83

There you go, three ways of cal­cu­lat­ing dis­tances in Blender’s Python.
Hope this saved you some googling!

All the posts you can read
TutorialsBlender, Python26.03.2020

No comments yet

Leave a Reply

Your email address will not be published.