Code archives/3D Graphics - Maths/GetAngle for BlitzMax

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

Download source code

GetAngle for BlitzMax by P.Weijtenburg
(Posted 19 years ago)
With the function GetAngle() you can obtain the angle from point 1 to point 2. It has a small hack that returns the real angle unlike the return of ATan2, and can now be used in Sin() and Cos(). For example, in a 360/8/4 etc, directional movement.
Function GetAngle:Float(srcx:Float, srcy:Float, destx:Float, desty:Float) 
	Local angle:Float = ATan2(desty - srcy, destx - srcx) 
	If angle > 0 angle = 360 - angle
	Return Abs(angle) 
End Function

Comments

Doiron
(Posted 18 years ago)
In order to return the classic orientation where, given the source at x=0, y=0, the destination facing up north is 90°, shouldn't the function be like this?

Function GetAngle:Float(srcx:Float, srcy:Float, destx:Float, desty:Float) 
	Local angle:Float = ATan2(desty - srcy, destx - srcx)
	angle = angle - 180
	If angle > 0 angle = 360 - angle
	Return Abs(angle) 
End Function


Jesse
(Posted 18 years ago)
both of the formulas/functions do extra work. If you set the images to work naturally with the equation, those last steps are unnecessary. you will never get an angle > 360 or < -360. some one has yet to prove to me where it fails. if you add the returning angle to "SetRotation" it will work just fine so the correct way would be:
Function GetAngle:Float(srcx:Float, srcy:Float, destx:Float, desty:Float) 
	return ATan2(desty - srcy, destx - srcx)
End Function

and save yourselves some headaches.
the main problem most beginners make is that the "missile" images are not created with the angle pointing to the direction corresponding the logic. if drawing missiles they have to be created pointing to the right instead of up and everything else will work fluidly.
if you decide to keep your images pointing up then yust set rotation like this:
SetRotation angle-90


it works with missiles, rockets, spaceships, cars, etc.

Code Archives Forum