motorollin wrote:
I'm trying to calculate an angle given the distances between two objects:
int distx = playerx-x;
int disty = playery-y;
int angle = atan( disty/distx) * (180/3.14159265);
fprintf( stdout, "%d \n",angle );
Where x=100 y=100, playerx=0 and playery=0, the angle returned is 45 which sounds correct. But if the object is put on the opposite side (x=-100, y=-100) then the angle is still 45. What an I doing wrong?
--
moto
This is due to the nature of tan, and the way it is generally handled.
Given that the convention of angles existing thus:

And the graph of tan looks (roughly) like this:

The Tan of (for example) 45 degrees (tan(45)) = 1, but the tan of 180+45 degrees (Tan(225)) also = 1.
Consequently when doing an inverse tan of this value (arctan(1)) there are two possible angles which could be returned (45 and 225).
Conventionally, calculators will return values between -90 and 90 degrees for sin and tan, and 90 - 180 degrees for cos (both sin and cos have similar, albeit different, properties with regard to the full 360 degree range).
One way out would be to set up a series of "if" statements to compensate for this, adding the appropriate multiples of 90 degrees depending on which quadrant of the circle your object is located in.
I see you've already solved it with Karlos's help, but thought you might like the insight into why this occurs. :-)