Created
February 27, 2017 21:06
-
-
Save Kolenov/7a0ba72e058693ca3feefc43ae633e38 to your computer and use it in GitHub Desktop.
Vector for 2d space
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* A vector for 2d space. | |
* @param {integer} x - Center x coordinate. | |
* @param {integer} y - Center y coordinate. | |
* @param {integer} dx - Change in x. | |
* @param {integer} dy - Change in y. | |
*/ | |
function Vector(x, y, dx, dy) { | |
// position | |
this.x = x || 0; | |
this.y = y || 0; | |
// direction | |
this.dx = dx || 0; | |
this.dy = dy || 0; | |
} | |
/** | |
* Advance the vectors position by dx,dy | |
*/ | |
Vector.prototype.advance = function () { | |
this.x += this.dx; | |
this.y += this.dy; | |
}; | |
/** | |
* Get the minimum distance between two vectors | |
* @param {Vector} | |
* @return minDist | |
*/ | |
Vector.prototype.minDist = function (vec) { | |
var minDist = Infinity; | |
var max = Math.max(Math.abs(this.dx), Math.abs(this.dy), | |
Math.abs(vec.dx), Math.abs(vec.dy)); | |
var slice = 1 / max; | |
var x, y, distSquared; | |
// get the middle of each vector | |
var vec1 = {}, vec2 = {}; | |
vec1.x = this.x + this.width / 2; | |
vec1.y = this.y + this.height / 2; | |
vec2.x = vec.x + vec.width / 2; | |
vec2.y = vec.y + vec.height / 2; | |
for (var percent = 0; percent < 1; percent += slice) { | |
x = (vec1.x + this.dx * percent) - (vec2.x + vec.dx * percent); | |
y = (vec1.y + this.dy * percent) - (vec2.y + vec.dy * percent); | |
distSquared = x * x + y * y; | |
minDist = Math.min(minDist, distSquared); | |
} | |
return Math.sqrt(minDist); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment