How to caclulate an angle?
BlitzMax Forums/BlitzMax Programming/How to caclulate an angle?
| ||
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 |
| ||
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 |
| ||
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? |
| ||
Thank you, guys! You saved my day :-) |
| ||
I thought it took the "y" value first though? It does. |
| ||
...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 |