CP Notebook

← all snippets

SegmentDistance

75mm Returns the shortest distance between point p and the line segment from point s to e. 15mm

6 lines tested

Usage: Point<double> a, b(2,2), p(1,1); bool onSegment = segDist(a,b,p) < 1e-10;

Needs: "Point.h"

content/geometry/SegmentDistance.h — Ulf Lundstrom

typedef Point<double> P;
double segDist(P s, P e, P p) {
	if (s==e) return (p-s).dist();
	auto d = (e-s).dist2(), t = min(d,max(.0,(p-s).dot(e-s)));
	return ((p-s)*d-(e-s)*t).dist()/d;
}