user2029675
user2029675

Reputation: 255

How to find an angle from 2 points?

I have this method in my Java program:

public static float findAngle(float x1, float y1, float x2, float y2) {
    float deltaX = Math.abs(x1 - x2);
    float deltaY = Math.abs(y1 - y2);
    return (float)(Math.atan2(deltaY, deltaX) * 180 / Math.PI);
}

I got it from googling this issue. However, when put into practice, it splits so I only get 1-180, and after 180 it goes back to 1. How do I fix this?

Upvotes: 2

Views: 434

Answers (2)

user1854369
user1854369

Reputation: 68

public static float findAngle(float x1, float y1, float x2, float y2) {
    float deltaX = x1 - x2;
    float deltaY = y1 - y2;
    return (float)(Math.atan2(deltaY, deltaX) * 180 / Math.PI);
}

Upvotes: 1

ApproachingDarknessFish
ApproachingDarknessFish

Reputation: 14323

Don't call Math.abs. Negative numbers and positive numbers will give different results, so you want to preserve the sign of deltaX and deltaY.

Upvotes: 5

Related Questions