浏览代码

Add Polygon.projectPoint and Polygon.distanceSq (#374)

* Add Polygon.projectPoint and Polygon.distanceSq

* Add outside param to Polygon.distanceSq
trethaller 7 年之前
父节点
当前提交
0e6c5084b2
共有 1 个文件被更改,包括 39 次插入0 次删除
  1. 39 0
      h2d/col/Polygon.hx

+ 39 - 0
h2d/col/Polygon.hx

@@ -194,6 +194,45 @@ abstract Polygon(Array<Point>) from Array<Point> to Array<Point> {
 		return closest;
 	}
 
+	/**
+		Return the closest point on the edges of the polygon
+	**/
+	public function projectPoint(pt: h2d.col.Point) {
+		var p1 = points[points.length - 1];
+		var closestProj = null;
+		var minDistSq = 1e10;
+		for(p2 in points) {
+			var proj = new Segment(p1, p2).project(pt);
+			var distSq = proj.distanceSq(pt);
+			if(distSq < minDistSq) {
+				closestProj = proj;
+				minDistSq = distSq;
+			}
+			p1 = p2;
+		}
+		return closestProj;
+	}
+
+	/**
+		Return the squared distance of `pt` to the closest edge.
+		If outside is `true`, only return a positive value if `pt` is outside the polygon, zero otherwise
+		If outside is `false`, only return a positive value if `pt` is inside the polygon, zero otherwise
+	**/
+	public function distanceSq(pt : Point, ?outside : Bool) {
+		var p1 = points[points.length - 1];
+		var minDistSq = 1e10;
+		for(p2 in points) {
+			var s = new Segment(p1, p2);
+			if(outside == null || s.side(pt) < 0 == outside) {
+				var dist = s.distanceSq(pt);
+				if(dist < minDistSq)
+					minDistSq = dist;
+			}
+			p1 = p2;
+		}
+		return minDistSq == 1e10 ? 0. : minDistSq;
+	}
+
 	public function rayIntersection( r : h2d.col.Ray, ?pt : Point ) {
 		var dmin = 1E9;
 		var p0 = points[points.length - 1];