• Advertisement
Sign in to follow this  

Trigonometry in c++

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

If you intended to correct an error in the post then please contact us.

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 this post


Link to post
Share on other sites
Advertisement
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 this post


Link to post
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 this post


Link to post
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 this post


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

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement