- Home /
Angle calculation not working??
I've been trying to calculate the angle between two Vec2's, but for some reason the way i've learned to do it via trig isn't working, and instead is giving me completely incorrect angles (in radians, and between 0 and 2π, which is kinda good at least because that's the expected range, but the angle itself is seemingly placebo-random within that range). This is the method i'm using (please excuse the awful writing):
Anyone know why the heck this isn't working? I've tried this with Atan and Atan2, but neither works :/
This is the code i've been using (the object starts at origin, removing the need for subtraction beforehand):
float angle = Mathf.Atan(target_pos.y/target_pos.x);
Anyone know what i'm messing up? It's giving me really crazy angles, like negatives when it's in the 2nd quadrant -_-
If you know the start point s, and also the two target points t1, t2, then you don't need trig to work out the angle, you can use Vector3.Angle...
float angle will give you the value in Radians, not degrees. The conversion to degrees requires the additional line of code:
angle = angle * $$anonymous$$athf.Rad2Deg;
What only returns 90? Vector3.Angle can return values up to 180. However you can also add some clever code (that figures out which side of a line the new point is) to allow you to figure out the full angle.
I'm using radians, used to working with them more so everything else in my code is set up for that
Answer by tanoshimi · Nov 27, 2014 at 07:09 PM
"isn't working" doesn't give us much to go on when we can't see your code, know what value you expected, or got. Please post a reproducible example. You are working with radians, right?
Sorry, I guess [code] [/code] doesn't work... I'll make the code a bit more visible and rephrase the first part
Answer by zharik86 · Nov 27, 2014 at 07:26 PM
For most case, better use Mathf.Atan2:
float angle = Mathf.Atan2(target_pos.y, target_pos.x); //return angle in radians
But, in your line can be devision by 0 (target_pos.x = 0). Of course, you have exception. In Atan2() in this case angle is equal 90 degree. I hope that it will help you.