Java Distance Calculate distanceToSegment(float ax, float ay, float bx, float by, float px, float py)

Here you can find the source of distanceToSegment(float ax, float ay, float bx, float by, float px, float py)

Description

distance To Segment

License

Open Source License

Parameter

Parameter Description
ax a parameter
ay a parameter
bx a parameter
by a parameter
px a parameter
py a parameter

Return

The distance from p to the line segment a-b

Declaration

public static float distanceToSegment(float ax, float ay, float bx, float by, float px, float py) 

Method Source Code

//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));
    }
}

Related

  1. distanceTo(final int x, final int y, final int thatx, final int thaty)
  2. distanceToAncestor(Class entity, Class ancestor)
  3. distanceToClass(Class theClass, Class theAncestor)
  4. distanceToInterface(Class theClass, Class theInterface)
  5. distanceToPoint(float x1, float y1, float x2, float y2)
  6. distanceToSegmentSquared(float px, float py, float vx, float vy, float wx, float wy)
  7. distanceVincenty(final double lat1, final double lon1, final double lat2, final double lon2)
  8. distancia(int[] c1, int[] c2)
  9. distAngle(double[] pos1, double[] pos2)