If this is a top-down game then you need to find the point P on the (enemy) square that is closest to the turret T. Then check the distance between P and the T. If the enemies were circles then this would be an easy problem to solve--but because they're squares then it's a bit trickier.

Here's my solution. Note that it requires some vector algebra.

1. You can assume the closest point will be on one of the edges. Define four vectors, one for each edge.

2. For each edge vector compute the point on the vector that is closest to the turret.

3. If any of the distances computed in step 2 are within range then the enemy is within range of the turret.

Here's my code where I implemented this, but you would need to make a "VPoint2D" class. You might be able to use

b2Vec2 instead (replace all references to VPoint2D with b2Vec2). I haven't tried it.

` // Project the point onto the vector uv`

public static function project( u:VPoint2D, v:VPoint2D, x:Float, y:Float ):VPoint2D

{

var seg = new VPoint2D( v.x - u.x, v.y - u.y );

var pt = new VPoint2D( x - u.x, y - u.y );

var seg_len = seg.length( );

if ( seg_len == 0 )

{

VallasIsometric.vallasError( "2D01", "Zero length projection" );

return u;

}

var proj_len:Float = pt.dot( seg ) / seg_len;

if ( proj_len < 0 )

return u;

if ( proj_len > seg_len )

return v;

return new VPoint2D( seg.x * proj_len / seg_len, seg.y * proj_len / seg_len );

}

// Return the point on the vector uv closest to (x,y)

public static function closestPoint( u:VPoint2D, v:VPoint2D, x:Float, y:Float ):VPoint2D

{

var proj:VPoint2D = VPoint2D.project( u, v, x, y );

return new VPoint2D( proj.x + u.x, proj.y + u.y );

}

Call the point returned by closestPoint P2. Check the distance between T and P2 and if it is within range then the turret can fire (to be more realistic, it shouldn't fire at the center, since it's still out of range. The turret should fire toward P2).

Another solution that would be less elegant would be to attach a larger, invisible actor to the enemies that acts as a sensor. When the "sensor actor" collides with the turret, then it triggers firing.