Welcome, Guest. Please login or register.

Author Topic: C++ Trigonometry  (Read 5593 times)

Description:

0 Members and 1 Guest are viewing this topic.

Offline Boot_WB

  • Hero Member
  • *****
  • Join Date: Feb 2005
  • Posts: 1326
    • Show all replies
    • http://www.hullchimneyservices.co.uk
Re: C++ Trigonometry
« on: September 11, 2007, 11:03:28 PM »
Quote

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. :-)
Mac Mini G4 (1.5GHz, 64MB VRam, 1GB Ram): MorphOS 3.6
Powerbook 5.8 (15", 1.67GHz, 128MB VRam, 1GB Ram): MorphOS 3.8.

Windows-free since 2011-2014 (Damn you Netflix!)
 

Offline Boot_WB

  • Hero Member
  • *****
  • Join Date: Feb 2005
  • Posts: 1326
    • Show all replies
    • http://www.hullchimneyservices.co.uk
Re: C++ Trigonometry
« Reply #1 on: September 11, 2007, 11:06:53 PM »
Just noticed - a topic on C++ Trigonometry, and only 14 people have viewed it!
Call yourselves geeks? :lol:
Mac Mini G4 (1.5GHz, 64MB VRam, 1GB Ram): MorphOS 3.6
Powerbook 5.8 (15", 1.67GHz, 128MB VRam, 1GB Ram): MorphOS 3.8.

Windows-free since 2011-2014 (Damn you Netflix!)