In case Flash no longer exists; a copy of this site is included in the Flashpoint archive's "ultimate" collection.

Dead Code Preservation :: Archived AS3 works from wonderfl.net

Closest point between circle and line segment

Get Adobe Flash player
by mutantleg 01 Feb 2012
/**
 * Copyright mutantleg ( http://wonderfl.net/user/mutantleg )
 * MIT License ( http://www.opensource.org/licenses/mit-license.php )
 * Downloaded from: http://wonderfl.net/c/c8Yi
 */

package {
    import flash.events.Event;
    import flash.display.Sprite;
    public class FlashTest extends Sprite {
        
        public function FlashTest() {
            // write as3 code here..
        
            addEventListener(Event.ENTER_FRAME, onEnter);    
        }//ctor
        
        //circle
        public var cx:Number = 0;
        public var cy:Number = 0;
        public var cr:Number = 32;
        
        //line (segment)
        public var ax:Number = 52;
        public var ay:Number = 33;
        public var bx:Number = 230;
        public var by:Number = 220;
        
        public function onEnter(e:Event):void
        {
            cx = this.mouseX;
            cy = this.mouseY;
            
            
            graphics.clear();
            graphics.lineStyle(1,0);
            
            graphics.drawCircle(cx,cy, cr);
            
            graphics.moveTo(ax,ay);
            graphics.lineTo(bx,by);
            
           
            
            var t:Number;
            var dx:Number;
            var dy:Number;
            //var mag:Number;
            var ix:Number;
            var iy:Number;
            var vx:Number;
            var vy:Number;
            //var px:Number;
            //var py:Number;
            var dotv:Number;
            
            vx = bx - ax;
            vy = by - ay;
            
            dx = cx - ax;
            dy = cy - ay;
            
            dotv = vx*dx + vy*dy;
            t = dotv / (vx*vx + vy*vy);
            if (t < 0) { t= 0;}
             if (t > 1.0) {t = 1.0;}
             ix = ax + vx*t;
             iy = ay +vy *t;
             
            
            
            
            
            graphics.lineStyle(1,0xFFFF0000);
            graphics.drawCircle(ix, iy, 8);
            
            graphics.moveTo(ix,iy);
            graphics.lineTo(cx,cy);
            
            
        }//onenter
        
        
    }//classend
}//package