"Drag and Drop" behavior is easy to do in ActionScript, but sometimes it would be cooler if you could limit or constrain the dragging movement of an object to a line. This opens the door for implementing
more creative interaction design...

 
/*---------------------------------------------------------------------------
Returns the closest Point on Line "AB" to Point "p":
 
p			-Point, the Point to constrain to the line.
A			-Point, beginning Point of Line.
B			-Point, ending Point of Line.
as_seg	-Boolean, limits return Point between endpoints of A and B.
----------------------------------------------------------------------------*/
function constrainPointToLine(p:Point,A:Point,B:Point,as_seg:Boolean=false):Point
{
    var cp:Point=new Point();
    var dx:Number;
    var dy:Number;
    var t:Number;
 
    dx = B.x - A.x;
    dy = B.y - A.y;
    if (dx == 0 && dy == 0) {
        cp.x = A.x;
        cp.y = A.y;
    }else{
        t = ((p.x - A.x) * dx + (p.y - A.y) * dy) / (dx * dx + dy * dy);
        if (as_seg){
			t = Math.min(Math.max(0,t),1);
		}
        cp.x = A.x + t * dx;
        cp.y = A.y + t * dy;
    }
    return cp;
}
 
Vote in HexoSearch
One Response to “Constrain a Point to a Line”
  1. Thanks for sharing this code snippet! I found this pretty useful when trying to manually constrain a rectangle’s resize dimensions with a corner drag button.

Leave a Comment

Thanks for visiting www.keith-hair.net