Calculating distances in Blender with Python
In this super quick tip we’ll see how to calculate the distance between two points. The formula for Euclidean distance in 3D is the following:
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 - point1) ** 2 + (point2 - point1) ** 2 + (point2 - point1) ** 2)
The benefit of this snippet is that it will always be available. It doesn’t depend on a specific Python version or Blender modules. The downside is lower performance and having 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 convenient class called
Vector. I could write for hours how much I like this class, but let’s stick to distances.
We can easily find the distance between two vectors by subtracting them, and then checking the length property of the resulting vector. All blender coordinates are vectors. But if you need to make one you can just pass a tuple or list of numbers to
Not only is this shorter, but it’s also faster since it’s running on C internally. On top of that, you can make vectors of any dimension whether it’s 2D or 26D (for those of you working with string theory 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 function that can calculate distances for iterables of any dimension. You can also drop Vectors here, as well as the usual Lists and Tuples. This way will probably become the standard Python Way™ and you’ll find it in libraries and such. It’s also useful to have if you are mixing different kinds of objects since it will take anything that can be iterated.
If you want to feel smart, the old Pythagorean Theorem method has also been updated. The
hypot() function used to take only 2 coordinates, but now it can take any number of them. There’s no reason to do this anymore really.
Python 3.8 will find its way to Blender in 2.83
There you go, three ways of calculating distances in Blender’s Python.
Hope this saved you some googling!
No comments yet