[AS 2.0] Distance Functions
First code posting, this is going to messy.... (attempt #2)
/* Returns the distance between two MovieClips */
function getDistanceMC(mc1:MovieClip, mc2:MovieClip):Number {
var dx:Number = mc2._x - mc1._x;
var dy:Number = mc2._y - mc1._y;
var d:Number = Math.sqrt((dx * dx) + (dy * dy));
return d;
}
/* Returns the distance between two points (x, y) */
function getDistanceXY(x1:Number, y1:Number, x2:Number, y2:Number):Number {
var dx:Number = x2 - x1;
var dy:Number = y2 - y1;
var d:Number = Math.sqrt((dx * dx) + (dy * dy));
return d;
}
/*
// Returns the position in given array of the closest MovieClip
// to given MovieClip. Returns Null if the closest is 0, the
// array is empty, the only MovieClip in the array is the given
// MovieClip.
//
// Array Format: [mc1, mc2, mc3, mcn, ...]
//
// Dependencies: getDistanceMC();
*/
function getClosestMC(mc_array:Array, mc:MovieClip):Number {
var aNum:Number;
var cDist:Number;
var lDist:Number = Infinity;
for(var i = 0; i < mc_array.length; i++){
if(mc_array[i] != mc){
var cDist = getDistanceMC(mc, mc_array[i]);
if(cDist < lDist){
lDist = cDist;
aNum = i;
}
}
}
return aNum == undefined ? null : aNum;
}
/*
// Returns the position in given array of the closest point
// to given x, y coordinates. Returns Null if the closest is 0,
// the array is empty, the only point in the array is the same
// as given coordinates.
//
// Array format: [{x:10, y:10}, {x:20, y:20}, {x:15, y:15}, ...];
//
// Dependencies: getDistanceXY();
*/
function getClosestXY(xy_array:Array, x:Number,y:Number):Number {
var aNum:Number;
var cDist:Number;
var lDist:Number = Infinity;
for(var i = 0; i < xy_array.length; i++){
var cDist = getDistanceXY(xy_array[i].x, xy_array[i].y, x, y);
if((cDist < lDist) && (cDist > 0)){
lDist = cDist;
aNum = i;
}
}
return aNum == undefined ? null : aNum;
}