Both methods you posted here are horribly inefficient. Only difference is that the tutorial Bags159 linked to is using data editor and the trigger is doing the exact same calculations, but in script. The problem here is the (closest unit to point) function, that propably cycles through every unit in map and compares distance. 50 times!
What you should do is use
Point to line distance formula, and apply this formula to every unit in possible area (the orange circle).
This way, you will reduce calculations to ONE "pick units" and some calculations (calculating distance are two multiplikations and 3 additions - very fast)
The formula itself: First, you need to calculate the line vector. If you have unit facing, the vector is
( Sin(face), Cos(Face) ). Then you convert it to
normal vector (which is perpendicular to the line vector) - switch the both values and multiply one of them by -1.
You will get something like (Cos(face), -Sin(face) ). Now it's really easy.
If you calculate
dot product, you will get distance from line (
dot product - multiply X with the first number (Cos), y with the second (-Sin) and add them both - very simple).
So the last step is easy, calculate distance of the attacker position and compare it with targets position to get the real distance
Code:
x1 = Cos(facing)
y1 = - Sin(facing)
attackerDist = (X of Attacker) * x1 + (Y of Attacker) * y1
Pick all units in the area ( circle, radius is range/2, center is (Position of attacker)+(-y1*range/2,x1*range/2) )
distDiff = (X of PickedUnit)*x1 + (Y of PickedUnit)*y2) - attackerDist
if( Abs( distDiff ) < shotRadius )
target = picked unit