Here you can find the source of distanceToSegment(float ax, float ay, float bx, float by, float px, float py)
Parameter | Description |
---|---|
ax | a parameter |
ay | a parameter |
bx | a parameter |
by | a parameter |
px | a parameter |
py | a parameter |
public static float distanceToSegment(float ax, float ay, float bx, float by, float px, float py)
//package com.java2s; public class Main { /**/*from w ww .j a va2 s . co m*/ * @param ax * @param ay * @param bx * @param by * @param px * @param py * @return The distance from p to the line segment a-b */ public static float distanceToSegment(float ax, float ay, float bx, float by, float px, float py) { float vx = bx - ax; float vy = by - ay; float wx = px - ax; float wy = py - ay; double c1 = wx * vx + wy * vy; double c2 = vx * vx + vy * vy; if (c1 <= 0) { return (float) Math.hypot((ax - px), (ay - py)); } if (c1 >= c2) { return (float) Math.hypot(bx - px, (by - py)); } double b = c1 / c2; vx *= b; vy *= b; vx += ax; vy += ay; return (float) Math.hypot((vx - px), (vy - py)); } }