Skip to content

Instantly share code, notes, and snippets.

@TheGreatRambler
Last active December 20, 2017 22:50
Show Gist options
  • Save TheGreatRambler/d89d9d328a4154b3eb5ecff8920bf92f to your computer and use it in GitHub Desktop.
Save TheGreatRambler/d89d9d328a4154b3eb5ecff8920bf92f to your computer and use it in GitHub Desktop.
Simple function to get distance between two points with an added twist --- in order to prevent performance problems with squaring large numbers and getting the square root of their addition, the smallest x and y values are set as zero and the largest are set as the difference between the two points. This way, the performance is better.
function distancebetweentwopoints(x1, y1, x2, y2) {
if (x1 > x2) {
x1 = x1 - x2;
x2 = 0;
} else {
x2 = x2 - x1;
x1 = 0;
}
if (y1 > y2) {
y1 = y1 - y2;
y2 = 0;
} else {
y2 = y2 - y1;
y1 = 0;
}
var xs = Math.pow(x2 - x1, 2);
var ys = Math.pow(y2 - y1, 2);
return Math.sqrt( xs + ys );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment