How to write an ATan2( ) function?
Blitz3D Forums/Blitz3D Programming/How to write an ATan2( ) function?
| ||
I am compiling a 3D vector and quarternion lib in PB, which has an ATan() but no ATan2() function. Can anyone tell me how to write an ATan2() function? |
| ||
Got it. I didn't realize it was such a simple thing. Procedure.f ATan2(y.f,x.f) a.f=ATan(y.f/x.f) If x.f<0.0 a.f=180.0+a.f EndIf If a.f>180.0 a.f=a.f-360.0 EndIf ProcedureReturn a.f Endprocedure |
| ||
I think it would be something along these lines: ATan2() would take two parameters (y#, x#) and return the arctangent of y/x. The way I understand it, it's a "quadrant-specific" version of arctangent... If x = 0 And y = 0 Then Return FAIL If x = 0 And y > 0 Then Return 90 If x = 0 And y < 0 Then Return -90 If x > 0 And y = 0 Then Return 0 If x > 0 And y <> 0 Then Return ATan(y/x) If x < 0 And y = 0 Then Return 180 If x < 0 And y <> 0 Then Return (180 - ATan(Abs(y) / Abs(x))) * Sgn(Y) Test that out (and optimize it) before you use it. <EDIT> Whoops, that's what I get for waiting to reply... |
| ||
Hi, That's not quite right Halo. What you need to do is look at the sign of the 2 arguments to work out which 'quadrant' the 2d vector is pointing into. You then adjust the result of Atan correspondingly. The problem with plain Atan is that it only has one 'sign' to go on. |
| ||
Procedure.f ATan2(y.f,x.f) a.f=ATan(y.f/x.f) That code will give you a divide by 0 error if X is 0. |