Reputation: 4026
I have two points in a cathesian 2D system, both give me the start and end point of a vector. Now i need the angle between the new vector and the x-axis.
I know that gradient = (y2-y1) / (x2-x1) and i know that angle = arctan(gradient).
But i dont know if this works for every case (direction) the vector takes. When do i need to add 180 degrees or something like that.
can anyone provide me with some c / java like code or hints for all the cases.
Thx and best regards
Upvotes: 3
Views: 12367
Reputation: 5487
So to summarize, when you have a 2D xy vector and need to find a 0\360 degree to the positive X-Axis you do this:
const float RAD2DEG = 180.0f / 3.14159f;
float x = -4.0f;
float y = 3.2f;
// atan2 receives first Y second X
double angle = atan2(y, x) * RAD2DEG;
if (angle < 0) angle += 360.0f;
Upvotes: 1
Reputation: 1213
You could use the dot product (http://en.wikipedia.org/wiki/Dot_product) but simplifying it all out, you end up just taking the arctangent of the endpoint of your vector to get the angle between it and the x axis. Atan functions usually return on the order [-pi,pi] or [-180,180], so if you're looking to make sure it wraps correctly, you'll need to check to see if the y-component of your vector is negative. In C, you can use atan2 instead of atan, and it'll use the sign of each component to figure out the sign of the angle (http://www.cplusplus.com/reference/clibrary/cmath/atan2/).
For example, if you have the vector points start=<1,2> and end=<-5,-5>, adjust it back to the origin by subtracting the start from the end, giving you <-6,-7>. So you're looking at that point. The angle with the x-axis is atan2(y,x), atan2(-7,-6), which is -130.6.
double x = -6;
double y = -7;
fprintf(stderr,"angle is %.2f\n",atan2(y,x)*180/3.14159);
angle is -130.60
Upvotes: 7