May
27
2009

## Knowing if a Point is behind a Line

Posted by: Keith H in ActionScript 3, SciFi, tags: Behind, Line, Points, TestYea yea, I know Battlestar Galactica is over, but today I thought of the "Daybreak part 1" episode of BSG.

Hera, a little girl has been kidnapped by the Cylons. As part of a desperate plan to save Hera, Admiral Adama draws a red line on the deck, and asks for those willing to risk their lives to save her, do so by crossing the line.

I had a similar problem also with my scripts. I wanted to simply know if a Point was behind a Line or not...

/*----------------------------------------------------------------- Returns true if Point P is behind line defined by Points C and D. ----------------------------------------------------------------*/ function isBehindLine(P:Point,C:Point,D:Point):Boolean { var a:Number=Point.distance(P,C.add(Point.polar(1,Math.atan2(C.y - D.y,C.x - D.x) + Math.PI / 2))); var b:Number=Point.distance(P,C.add(Point.polar(-1,Math.atan2(C.y - D.y,C.x - D.x) + Math.PI / 2))); return a < b; }

[...] « Knowing if a Point is behind a Line May 28 2009 [...]

Optimizations:

1. Store Math.PI in a class variable.

Ex: private const MATH_PI:Number = Math.PI;

2.Calculate Math.atan2 only ONCE since you are using it with identical values on

both lines. This means you are doing two unneccessary subtractions and 1 unneccessary

call to Math.atan2. Math library calls are infamously slow.

Ex: var deltaAtan:Number = Math.atan2(C.y-D.y, C.x-D.x);

3. Whenever you can MULTIPLY rather than DIVIDE:

Multiply by .5 rather than divide by 2.

4. EDIT while writing you optimized code:

Store Math.PI / 2 in a constant variable.

function isBehindLine(P:Point,C:Point,D:Point):Boolean

{

var halfPI :Number = Math.PI * 0.5;

var deltaAtan:Number = Math.atan2(C.y – D.y,C.x – D.x );

var a:Number=Point.distance(P,C.add(Point.polar( 1,deltaAtan + halfPI )));

var b:Number=Point.distance(P,C.add(Point.polar(-1,deltaAtan + halfPI )));

return a < b;

}