Java Geometry Algorithm hitsLine(final Point2D p, final Point2D fromPoint, final Point2D toPoint, final double thickness)

Here you can find the source of hitsLine(final Point2D p, final Point2D fromPoint, final Point2D toPoint, final double thickness)

Description

Whether a point is on a line of a given thickness.

License

Open Source License

Parameter

Parameter Description
p point in question.
fromPoint one end of line.
toPoint other end of line.
thickness thickness of the line.

Return

true if on the line, false otherwise.

Declaration

public static boolean hitsLine(final Point2D p, final Point2D fromPoint, final Point2D toPoint,
        final double thickness) 

Method Source Code


//package com.java2s;
import java.awt.geom.Point2D;

public class Main {
    /**/*from w  ww.  ja  v a  2s . co m*/
     * Whether a point is on a line of a given thickness.
     * @param p point in question.
     * @param fromPoint one end of line.
     * @param toPoint other end of line.
     * @param thickness thickness of the line.
     * @return true if on the line, false otherwise.
     */
    public static boolean hitsLine(final Point2D p, final Point2D fromPoint, final Point2D toPoint,
            final double thickness) {
        if ((fromPoint == null) || (toPoint == null)) {
            return false;
        }
        double vx0 = fromPoint.getX();
        double vy0 = fromPoint.getY();
        double vx1 = toPoint.getX();
        double vy1 = toPoint.getY();
        double vx2 = p.getX();
        double vy2 = p.getY();

        double minX = Math.min(vx0, vx1) - thickness / 2;
        double maxX = Math.max(vx0, vx1) + thickness / 2;
        double minY = Math.min(vy0, vy1) - thickness / 2;
        double maxY = Math.max(vy0, vy1) + thickness / 2;

        if ((vx2 > maxX) || (vx2 < minX)) {
            return false;
        }
        if ((vy2 > maxY) || (vy2 < minY)) {
            return false;
        }

        // Calculate magnitude of the normal to the line-segment
        double magNormal = Math.sqrt(((vx1 - vx0) * (vx1 - vx0)) + ((vy1 - vy0) * (vy1 - vy0)));

        // Calculate (signed) distance of the point from the line-segment
        double distance = (((vx2 - vx0) * (vy0 - vy1)) + ((vy2 - vy0) * (vx1 - vx0))) / magNormal;

        // Check if the
        if (Math.abs(distance) <= (thickness / 2)) {
            return true;
        }
        return false;
    }
}

Related

  1. generateLookAtTag(ArrayList geoCoords, ArrayList modsAM)
  2. generatePoint(Shape region)
  3. generateRobotPositions(Point start, Point end, int stepSize)
  4. generateSpline(final Point[] controls)
  5. gridAlign(final Point2D point, final double gridX, final double gridY)
  6. insidePoly(Polygon pg, Point p)
  7. interceptLineAndBox(Point2D startPosition, Point2D endPosition, RectangularShape boundingBox)
  8. interpol(Point p1, Point p2, float factor)
  9. invVec(final Point2D v)