returns the angle between (x, y) and (origin X, origin Y). - Java java.lang

Java examples for java.lang:Math Geometry Shape

Description

returns the angle between (x, y) and (origin X, origin Y).

Demo Code

/*/*from ww  w  . j  ava 2 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.
 */
//package com.java2s;
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 Tutorials