Created
March 24, 2023 22:17
-
-
Save h4k1m0u/7a7cfd060299dbe8835d53ec2eb8f997 to your computer and use it in GitHub Desktop.
Calculate the distance between two segments identified by a pair of extremity 2D points
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# this script is meant to be run inside Blender | |
import math | |
from mathutils import Vector, geometry | |
def distance_point_to_segment(p, p0, p1): | |
""" | |
Project point p on line passing through points p0 and p1 | |
Returns Distance between point p & its projection, if the latter belongs to segment p0-p1, | |
Infinity otherwise | |
""" | |
# percentage gives the dist from the 1st line point to the proj. point => in [0, 1] if in segment | |
p_proj, percentage = geometry.intersect_point_line(p, p0, p1) | |
dist = (p_proj - p).length | |
print('### p:', p) | |
print('proj:', p_proj) | |
print('percentage:', percentage) | |
print('dist:', dist) | |
print() | |
return dist if 0 <= percentage <= 1 else math.inf | |
if __name__ == '__main__': | |
# 1st line: y = x | |
p0 = Vector((0, 0)) | |
p1 = Vector((2, 2)) | |
# 2nd line: y = 2x | |
p2 = Vector((1, 2)) # for when proj. inside segments! | |
p3 = Vector((2, 4)) | |
# p2 = Vector((2, 4)) # for when proj. outside segments! | |
# p3 = Vector((3, 6)) | |
# project of points p0/p1 (from 1st line) on 2nd line | |
dist0 = distance_point_to_segment(p0, p2, p3) | |
dist1 = distance_point_to_segment(p1, p2, p3) | |
# project of p2/p3 (from 2nd line) on 1st line line | |
dist2 = distance_point_to_segment(p2, p0, p1) | |
dist3 = distance_point_to_segment(p3, p0, p1) | |
# dist = inf if all proj. points outside segments | |
dists = [ dist0, dist1, dist2, dist3 ] | |
dist = min(dists) | |
# in this case dist = min dist. between segments extremities | |
if dist == math.inf: | |
print('All projected points outside segments') | |
dists = [ | |
(p0 - p2).length, | |
(p0 - p3).length, | |
(p1 - p2).length, | |
(p1 - p3).length, | |
] | |
dist = min(dists) | |
print('Dist:', dist) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment