Given a line segment the rotation (from a pointing straight up position) in radians of that line. - Java 2D Graphics

Java examples for 2D Graphics:Line

Description

Given a line segment the rotation (from a pointing straight up position) in radians of that line.

Demo Code


//package com.java2s;

public class Main {
    /**//from   w  ww.j a  v a2s . c o  m
     * Given a line segment the rotation (from a pointing straight up position) in radians of that line.
     * 
     * @param x1 The first x coordinate
     * @param y1 The first y coordinate
     * @param x2 The second x coordinate
     * @param y2 The second y coordinate
     * @return The rotation in radians of the line described by the line segment provided
     */
    public static double getLineRotation(double x1, double y1, double x2,
            double y2) {
        double dx = x2 - x1;
        double dy = y1 - y2;
        double length = Math.sqrt((dx * dx) + (dy * dy));
        double xRatio = dx / length;
        double r1 = Math.asin(Math.abs(xRatio));
        if (dx > 0) {
            double r2 = Math.PI / 2 + (Math.PI / 2 - r1);
            if (y1 > y2) { // Pointing up a bit
                return r1;
            } else {
                return r2;
            }
        } else {
            double r2 = Math.PI * 1.5 + (Math.PI / 2 - r1);
            r1 = Math.PI + r1;
            if (y1 < y2) { // Pointing down a bit
                return r1;
            } else {
                return r2;
            }
        }
    }
}

Related Tutorials