Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
596 views
in Technique[技术] by (71.8m points)

lines - Calculating angle between two points - java

I need to calculate the angle in degrees between two points, with a fixed point that is connected with the given two points by a line.

Here is an image that illustrates what I need:

enter image description here

Here is what I have tried so far:

public static float GetAngleOfLineBetweenTwoPoints(float x1, float x2, float y1, float y2) {
        float xDiff = x2 - x1;
        float yDiff = y2 - y1;
        return (float) (Math.atan2(yDiff, xDiff) * (180 / Math.PI));
}

It's pointless to say that it doesn't provide the correct answer.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can have the following method that calculates the angle in radians using the Math.atan2 method:

public static double angleBetweenTwoPointsWithFixedPoint(double point1X, double point1Y, 
        double point2X, double point2Y, 
        double fixedX, double fixedY) {

    double angle1 = Math.atan2(point1Y - fixedY, point1X - fixedX);
    double angle2 = Math.atan2(point2Y - fixedY, point2X - fixedX);

    return angle1 - angle2; 
}

And call it with three points (using Math.toDregrees to transform resulting angle from radians to degrees):

System.out.println(Math.toDegrees(
            angleBetweenTwoPointsWithFixedPoint(0, 0, // point 1's x and y
                                                1, 1, // point 2
                                                1, 0  // fixed point
                                               )));

Output: 90.0

Feel free to use Java's standard Point or Line2D classes in your solution though. This was just to demonstrate it works.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...