Blitz3D+ Command Reference

ATan2# ( floata#,floatb# )

Parameters

floata - the y (vertical) component of the direction

floatb - the x (horizontal) component of the direction

Description

Returns the angle of the direction (x,y), in degrees, over the full circle.

Note the argument order: the y component comes first, then x. That trips everybody up at least once. ATan2( y,x ) is the "smart" version of ATan( y/x ) - by looking at the two components separately it can tell which quadrant you are in, so it returns an angle greater than -180 and up to +180 degrees instead of being stuck in a half-turn.

This is the command you want for aiming. To point a turret, a homing missile or a sprite at a target, take ATan2( target_y-my_y,target_x-my_x ) and you have the heading in degrees. It also handles a zero x component cleanly, where the plain ATan( y/x ) version would divide by zero.

Remember that screen y grows downwards while world y usually grows upwards, so the same maths gives a mirrored angle in 2D and 3D. If your sprites aim the wrong way vertically, negate the y component you pass in.

See also: ATan, ASin, ACos, Sin, Cos.

Example

; ATan2 Example
; -------------

Graphics 640,480,0,2
SetBuffer BackBuffer()

; ATan2(dy,dx) gives the angle, in DEGREES, from one point towards
; another - perfect for aiming. Note the order: the y difference comes
; FIRST. The result runs from -180 to +180, covering the full circle
; (plain ATan only manages -90 to +90).

; The turret sits at the centre of the screen
tx=320
ty=240

While Not KeyDown(1)

    ; Aim the turret at the mouse
    dx=MouseX()-tx
    dy=MouseY()-ty
    angle#=ATan2(dy,dx)

    Cls

    ; Turret base
    Color 100,100,255
    Oval tx-16,ty-16,32,32,True

    ; The barrel points along the ATan2 angle
    ; (Cos/Sin turn the angle back into a direction)
    Color 255,255,0
    Line tx,ty,tx+50*Cos(angle),ty+50*Sin(angle)

    ; Crosshair on the mouse
    Color 255,0,0
    Oval MouseX()-5,MouseY()-5,10,10,False

    Color 255,255,255
    Text 0,0,"Move the mouse - the turret tracks it   Esc: exit"
    Text 0,20,"ATan2("+dy+","+dx+") = "+angle

    Flip

Wend

End

Index