Java Angle from Point getAngle(double originX, double originY, double x, double y)

Here you can find the source of getAngle(double originX, double originY, double x, double y)

Description

The getAngle method returns the angle between (x, y) and (originX, originY).

License

Open Source License

Declaration

public static double getAngle(double originX, double originY, double x, double y) 

Method Source Code


//package com.java2s;
/*// w  w  w  .j  av  a2 s . c om
 * Copyright (c) JenSoft API
 * This source file is part of JenSoft API, All rights reserved.
 * JENSOFT PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 */

import java.awt.geom.Point2D;

public class Main {
    /**
     * The getAngle method returns the angle between (x, y) and (originX,
     * originY). The value returned will be in the range [0.0 : 2 * Math.PI). If
     * the point x, y overlaps the origin then 0.0 is returned. If the point has
     * a positive x and zero y then the value returned is 0.0. If the point has
     * a negative x and zero y then the value returned is Math.PI. If the point
     * has a zero x and positive y then the value returned is Math.PI / 2. If
     * the point has a zero x and negative y then the value returned is 3 *
     * Math.PI / 2.
     */
    public static double getAngle(double originX, double originY, double x, double y) {

        double adj = x - originX;
        double opp = y - originY;
        double rad = 0.0;

        if (adj == 0) {
            if (opp == 0) {
                return 0.0;
            } else {
                rad = Math.PI / 2;
            }
        } else {
            rad = Math.atan(opp / adj);
            if (rad < 0) {
                rad = -rad;
            }
        }

        if (x >= originX) {
            if (y < originY) {
                rad = 2 * Math.PI - rad;
            }
        } else {
            if (y < originY) {
                rad = Math.PI + rad;
            } else {
                rad = Math.PI - rad;
            }
        }
        return rad;
    }

    /**
     * Returns the angle between the origin and the specified point.
     * 
     * @see #getAngle(double,double,double,double)
     */
    public static double getAngle(Point2D origin, Point2D p) {
        return getAngle(origin.getX(), origin.getY(), p.getX(), p.getY());
    }
}

Related

  1. getAngle(Point2D center, Point2D point)
  2. getAngle(Point2D origin, Point2D target)
  3. getAngle(Point2D p1, Point2D p2)
  4. getAngle(Point2D startPosition, Point2D endPosition)