Computes minimum distance from line to point - Java 2D Graphics

Java examples for 2D Graphics:Point

Description

Computes minimum distance from line to point

Demo Code

/*//  www  . java  2s .c  o  m
 *  Flingbox - An OpenSource physics sandbox for Google's Android
 *  Copyright (C) 2009  Jon Ander Pe?alba & Endika Guti?rrez
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
import java.util.ArrayList;

public class Main{
    /**
     * Computes minimum distance from line to point
     */
    public static float distanceFromLineToPoint(final Vector2D p0,
            final Vector2D p1, final Vector2D p) {
        final float area = (p0.i * p1.j + p1.i * p.j + p.i * p0.j - p1.i
                * p0.j - p.i * p1.j - p0.i * p.j) / 2f;
        final float base = (float) Math.sqrt((p1.i - p0.i) * (p1.i - p0.i)
                + (p1.j - p0.j) * (p1.j - p0.j));
        return (float) Math.abs(2f * area / base);
    }
}

Related Tutorials