Computes the angle between two straight lines defined by three points Line 1: p1-p2 and line 2: p2-p3. - Java java.lang

Java examples for java.lang:Math Geometry Line

Description

Computes the angle between two straight lines defined by three points Line 1: p1-p2 and line 2: p2-p3.

Demo Code


import java.awt.geom.*;
import java.util.*;

public class Main{
    /**/*from w  w w .ja  va2 s  . c  o  m*/
     * Computes the angle between two straight lines defined by three points
     * Line 1: p1-p2 and line 2: p2-p3.
     * @return The angle between the two lines in radian between -pi and +pi.
     */
    public static double angle(double x1, double y1, double x2, double y2,
            double x3, double y3) {
        final double dx1 = x1 - x2;
        final double dy1 = y1 - y2;
        final double dx2 = x3 - x2;
        final double dy2 = y3 - y2;

        final double ang1 = Math.atan2(dx1, dy1);
        final double ang2 = Math.atan2(dx2, dy2);
        final double angle = ang2 - ang1;

        return GeometryUtils.trimAngle(angle);
    }
    public static double trimAngle(double angle) {
        if (angle > Math.PI) {
            return angle - 2. * Math.PI;
        }
        if (angle < -Math.PI) {
            return angle + 2. * Math.PI;
        }
        return angle;
    }
}

Related Tutorials