# Trigonometry in c++

This topic is 4813 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

ok, im not sure if this is the right forum to ask this in, but couldnt work out where else to post. my problem is that im trying to convert radians to degrees in c++ and i read everywhere u multiply them but 180/PI. so here is my function int GME_Object::FacePoint(float tx, float ty) { float ttx; float tty; ttx = (x+image->Width()/2)-tx; // abs() required? tty = (y+image->Height()/2)-ty; rotation = atan(tty / ttx)*180/M_PI; return rotation; } tx,ty is the target point to face. x,y is the current objects position ttx and tty were used because i thought unrolling the math would help me understand. rotation is the angle towards the target. it rotates about the middle of the image ( hence x+image->Width()) etc. the result of this code is that it rotates from -90 degrees ( when target is directly above -90 degrees = 0 for some unknown reason) smoothly and correctly through to 90 degrees then when the image is directly below, it snaps back to - 90 degrees. im sure this is a problem with my code, not ZEngine, but cant spot where or why the problem exists, any help would be greatly apprectiated.

##### Share on other sites
The behavior you're experiencing is probably because you're using arctan, which by (mathmatical) definition is bound to the range [-90,90]. I'm not sure how you would go about fixing it without some drastic modifications of your code; just wanted to let you know what was probably causing it to jump.

##### Share on other sites
Can't you simply use atan2? Take a look at it. It uses the signs of the two input values to get the correct radian quadrant.

- S

##### Share on other sites
You want to be using atan2(tty, ttx) which performs the divide, but also sees the signs of both arguments and can thus give a wider range of output values.

Edit: It honestly wasn't showing the post above when I wrote that

##### Share on other sites
haha, yeah, thanks a lot, atan2 worked a charm, thanks for all the help

##### Share on other sites
In addition to what's been said, atan2() also avoids a potential division by zero.

1. 1
2. 2
3. 3
Rutin
15
4. 4
khawk
13
5. 5
frob
12

• 9
• 9
• 11
• 11
• 23
• ### Forum Statistics

• Total Topics
633665
• Total Posts
3013247
×