Distance Between Point and Line (optimized)

Actionscript:
  1. /**
  2. Original function by Pieter Iserbyt:
  3. http://local.wasp.uwa.edu.au/~pbourke/geometry/pointline/DistancePoint.java
  4. from Paul Bourke's website:
  5. http://local.wasp.uwa.edu.au/~pbourke/geometry/pointline/
  6. */
  7. function pointToLineDist(x1:Number, y1:Number, x2:Number, y2:Number,x3:Number, y3:Number):Number {
  8.     var dx:Number=x2-x1;
  9.     var dy:Number=y2-y1;
  10.     if (dx==0&&dy==0) {
  11.         x2+=1;
  12.         y2+=1;
  13.         dx=dy=1;
  14.     }
  15.     var u:Number = ((x3 - x1) * dx + (y3 - y1) * dy) / (dx * dx + dy * dy);
  16.  
  17.     var closestX:Number;
  18.     var closestY:Number;
  19.     if (u<0) {
  20.         closestX=x1;
  21.         closestY=y1;
  22.     } else if (u> 1) {
  23.         closestX=x2;
  24.         closestY=y2;
  25.     } else {
  26.         closestX=x1+u*dx;
  27.         closestY=y1+u*dy;
  28.     }
  29.     dx=closestX-x3;
  30.     dy=closestY-y3;
  31.     return Math.sqrt(dx * dx +  dy * dy);
  32. }
  33.  
  34. /**
  35. Test out the function
  36. */
  37.  
  38. var dotA:Sprite = dot(100, 100);
  39. var dotB:Sprite = dot(200, 200);
  40. var dotC:Sprite = dot(150, 100, 0x0000FF);
  41. var txt:TextField = TextField(dotC.addChild(new TextField()));
  42. with(txt) x = 5, y = 5, autoSize = "left", selectable = false, mouseEnabled = false;
  43.  
  44. addEventListener(Event.ENTER_FRAME, onLoop);
  45. function onLoop(evt:Event):void {
  46.     graphics.clear();
  47.     graphics.lineStyle(0,0x000000);
  48.     graphics.moveTo(dotA.x, dotA.y);
  49.     graphics.lineTo(dotB.x, dotB.y);
  50.     txt.text = pointToLineDist(dotA.x, dotA.y, dotB.x, dotB.y, dotC.x, dotC.y).toFixed(2);
  51. }
  52.  
  53. // draggable dot
  54. function dot(xp:Number, yp:Number, col:uint = 0xFF0000, rad:Number=4):Sprite {
  55.     var s:Sprite = Sprite(addChild(new Sprite));
  56.     s.x = xp;
  57.     s.y = yp;
  58.     with(s.graphics) beginFill(col), drawCircle(0,0,rad);
  59.     s.buttonMode = true;
  60.     s.addEventListener(MouseEvent.MOUSE_DOWN, onDrag);
  61.     return s;
  62. }
  63. function onDrag(evt:MouseEvent):void { evt.currentTarget.startDrag() }
  64. stage.addEventListener(MouseEvent.MOUSE_UP, onUp);
  65. function onUp(evt:MouseEvent):void{stopDrag() }

This is the same as yesterdays post about the distance between a point and a line segment. I just took a few minutes to optimize the function - it runs close to 3X faster now. For more info see yesterdays post.

This entry was posted in Math, graphics algorithms, misc and tagged , , . Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

One Comment

  1. Mohan
    Posted January 4, 2012 at 7:38 am | Permalink

    Thank u very much , The code is working fine for me.

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*