How to caclulate an angle?

BlitzMax Forums/BlitzMax Programming/How to caclulate an angle?

maverick69(Posted 2005) [#1]
I want to point an object to the mouse pointer in the correct angle, but it seems that something is wrong with my formula I use, because the rectangle doesn't point in the exact direction sometimes. Also sometimes it complelty disappears from the screen.

Here's the code


Graphics 640,480

Local x:Float = 320
Local y:Float = 240

Local Angle:Float = 0

While (1)
	Cls
		
	Angle = ASin((MouseX() - x) / (y - MouseY()))
	SetRotation(Angle)
	DrawRect x-20,y-20,40,40
	SetRotation(0)
	DrawLine (x,y,MouseX(),MouseY())
	
	Flip
Wend



tonyg(Posted 2005) [#2]
You should be using atan2(x1-x1,y1-y2)
The handle for the rect is topleft so it has problems with
the rotations.
drawrect and handle
Graphics 640,480

Local x:Float = 320
Local y:Float = 240

Local Angle:Float = 0

While Not KeyHit(key_escape)
	Cls
		
	Angle = ATan2((MouseX() - x),(y - MouseY()))
	SetRotation(Angle)
	DrawRect x,y,40,40
	SetRotation(0)
	DrawLine (x,y,MouseX(),MouseY())
	
	Flip
Wend



taxlerendiosk(Posted 2005) [#3]
Try ATan2 instead of ASin. Look it up as it actually takes two arguments (y and x vector components).

Edit: Whoops, beaten by tonyg - I thought it took the "y" value first though?


maverick69(Posted 2005) [#4]
Thank you, guys! You saved my day :-)


FlameDuck(Posted 2005) [#5]
I thought it took the "y" value first though?
It does.


tonyg(Posted 2005) [#6]
...and with Sethandle suggested by Eikon...
Graphics 640,480

Local x:Float = 320
Local y:Float = 240

Local Angle:Float = 0
While Not KeyHit(key_escape)
	Cls
	SetHandle 20,20
	Angle = ATan2((MouseX() - x),(y - MouseY()))
	SetRotation(Angle)
	DrawRect x,y,40,40
	SetRotation(0)
	SetHandle 0,0
	DrawLine (x,y,MouseX(),MouseY())
	
	Flip
Wend