Yea 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... :)

  1.  
  2. /*-----------------------------------------------------------------
  3. Returns true if Point P is behind line defined by Points C and D.
  4.  ----------------------------------------------------------------*/
  5. function isBehindLine(P:Point,C:Point,D:Point):Boolean
  6. {
  7. var a:Number=Point.distance(P,C.add(Point.polar(1,Math.atan2(C.y - D.y,C.x - D.x) + Math.PI / 2)));
  8. var b:Number=Point.distance(P,C.add(Point.polar(-1,Math.atan2(C.y - D.y,C.x - D.x) + Math.PI / 2)));
  9. return a < b;
  10. }
  11.  
2 Responses to “Knowing if a Point is behind a Line”
  1. [...] « Knowing if a Point is behind a Line May 28 2009 [...]

  2. 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;
    }

Leave a Comment

Thanks for visiting www.keith-hair.net