2D rotation help

BlitzMax Forums/BlitzMax Programming/2D rotation help

slenkar(Posted 2010) [#1]
I use this to get the angle between 2 points:
Function GetAngle2D:Float(X1:Float,Y1:Float,X2:Float,Y2:Float)
Local dx# = x2 - x1
Local dy# = y2 - y1
Local ang=ATan2(dy#,dx#)

Return ang
End Function


but when the first object is turning toweards the 2nd object the result flips from 179 to -179 which means the first object can never turn in the right direction

Also when I make the angle from 1-360 it flips between 1 and 360


Czar Flavius(Posted 2010) [#2]
Is this any good?

Local my_position:TVec2 = get_owner().get_position()
Local target_position:TVec2 = _target.get_position()
Local dif_angle = (ATan2((-target_position.y + my_position.y), (-target_position.x + my_position.x)))
_target_angle = fix_angle(dif_angle) 'target is at this angle from me
Local sangle = subangle(dif_angle, get_angle()) 'the angle i need to turn is this

Function fix_angle:Float(angle:Float)
	If angle >= 0.0
		Return angle Mod 360.0
	Else
		Return angle - (360.0 * (angle/360.0 - 1.0))
	End If
End Function

Function subangle:Float(angle:Float, target:Float)
	Local a:Float = (angle-target)
	Local b:Float = (target-angle)
	If a < 0.0 Then a :+ 360.0
	If b < 0.0 Then b :+ 360.0
	If a < b Then Return -a Else Return b
End Function



slenkar(Posted 2010) [#3]
where is the get_angle() function?


Jesse(Posted 2010) [#4]
I don't know if this can help you but I put some chaser code in the code archives that does what you want but I don't know it might be to NERDy for you. ;):
http://www.blitzmax.com/codearcs/codearcs.php?code=2045
or this if that link does not work for you:
http://www.blitzbasic.com/codearcs/codearcs.php?code=2045


slenkar(Posted 2010) [#5]
thanks ill check it out, if its not too NERDy


Pete Rigz(Posted 2010) [#6]
One of these or both might help:

rem
	bbdoc: get the direction from 1 point to another
	returns: Angle of difference
	about: Thanks to "Snarkbait" for this little code snippit
end rem
Function GetDirection:Float(fromx:Float, fromy:Float, tox:Float, toy:Float)

	Return (ATan2(toy - fromy, tox - fromx) + 450) Mod 360
	
End Function

rem
	bbdoc: Get the difference between 2 angles
end rem
Function AngleDifference:Float(Angle1:Float, Angle2:Float)
	Local diff:Float = Abs((angle1 + 180 - angle2) Mod 360 - 180)
	If diff > 180 Return Abs(diff - 360) Else Return diff
End Function



Czar Flavius(Posted 2010) [#7]
Get_angle() is just a getter method to get the object's current direction.


slenkar(Posted 2010) [#8]
thanks all, i got it now, just make sure to rotate in the opposite direction if the angle difference is larger than 180