Code archives/Algorithms/Calc Angle Between Two Angles

This code has been declared by its author to be Public Domain code.

Download source code

Calc Angle Between Two Angles by Shagwana2005
I prolly just re-invented the wheel with this one ...

Function will return a float that will tell you what you need to add to Ang1 to reach Ang2. Returned value will be the shortest way as well. A negative values means counter clockwise and a posative value means clockwise. Should both angles passed be the same, 0 is returned.
'Calculate the angle from Ang1 to Ang2. Valid angle values must be 0.0 to 360.0
Function CalcAngle:Float(Ang1:Float,Ang2:Float)
  If Ang1=Ang2
    'No angle to compute
    Return 0.0
    Else
    'There is an angle to compute
    Local fDif:Float=(Ang2-Ang1)   
    If fDif>=180.0
      fDif=fDif-180.0    'Correct the half
      fDif=180.0-fDif    'Invert the half
      fDif=0-fDif        'Reverse direction
      Return fDif
      Else
      If fDif<=-180.0
        fDif=fDif+180.0    'Correct the half
        fDif=180.0+fDif    
        Return fDif
        EndIf
      EndIf
    Return fDif
    EndIf
  End Function

Comments

N2005
Reinventing the wheel or not, many people do not know how to do this, so this should be considerably valuable to anyone who needs code for this.


Beaker2005
How's this for doing exactly the same thing in less lines, and a little less math?:
Function CalcAngle:Float(Ang1:Float,Ang2:Float)
	Local fDif:Float = Ang2-Ang1   
	If fDif >= 180.0
		fDif :- 360.0
	Else
		If fDif <= -180.0
			fDif :+ 360.0
		EndIf
	EndIf
	Return fDif
End Function



puki2005
I have seen that code snippet of "Beaker's" before it is the one I would use. Well perhaps not exactly his - but it is a well known calculation.


Oddball2005
I got this code straight from the archive about a year ago but I'm not sure where abouts.
Function GetAngDiff#(ang1#,ang2#)
	Local diff#=ang2-ang1
	While diff>180
		diff=diff-360
	Wend
	While diff<-180
		diff=diff+360
	Wend
	Return diff
End Function
All the above methods are perfectly fine though.


Shagwana2005
There must be a million ways to do the same thing. Always intrested in seeing more ...


Code Archives Forum