Java examples for java.lang:Math Trigonometric Function
Compute the distance between a point and a segment.
/* /* w w w . ja v a 2s. c o m*/ * $Id$ * * Copyright (C) 2010-2011 Janus Core Developers * Copyright (C) 2012 St?phane GALLAND * * 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/>. */ public class Main{ /** Compute the distance between a point and a segment. * * @param p position of the point. * @param s1 position of the first point of the segment. * @param s2 position of the second point of the segment. * @return the distance beetween the point and the segment. */ public static final float distancePointToSegment(Point2f p, Point2f s1, Point2f s2) { float r_denomenator = (s2.getX() - s1.getX()) * (s2.getX() - s1.getX()) + (s2.getY() - s1.getY()) * (s2.getY() - s1.getY()); if (r_denomenator == 0f) return p.distance(s1); float r_numerator = (p.getX() - s1.getX()) * (s2.getX() - s1.getX()) + (p.getY() - s1.getY()) * (s2.getY() - s1.getY()); float ratio = r_numerator / r_denomenator; if (ratio <= 0.) { return (float) Math.sqrt((p.getX() - s1.getX()) * (p.getX() - s1.getX()) + (p.getY() - s1.getY()) * (p.getY() - s1.getY())); } if (ratio >= 1f) { return (float) Math.sqrt((p.getX() - s2.getX()) * (p.getX() - s2.getX()) + (p.getY() - s2.getY()) * (p.getY() - s2.getY())); } float s = ((s1.getY() - p.getY()) * (s2.getX() - s1.getX()) - (s1 .getX() - p.getX()) * (s2.getY() - s1.getY())) / r_denomenator; return (float) (Math.abs(s) * Math.sqrt(r_denomenator)); } }