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:
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.
You can have the following method that calculates the angle in radians using the
Math.atan2
method:And call it with three points (using
Math.toDregrees
to transform resulting angle from radians to degrees):Output: 90.0
Feel free to use Java's standard
Point
orLine2D
classes in your solution though. This was just to demonstrate it works.Here is a code snippet from my Android Gesture library. It works and is fully tested.
I don't know @user2288580 but even for simple, test-cases your code is failing.
firstPoint = (0,0) secondPoint = (0, 5), (5,5), (5,0), (5, -5) (0, -5) (-5, -5), (-5, 0)
Please see if this works for you @David -