1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74
|
var Vec2 = function(x, y) { this.x = x; this.y = y; }; Vec2.prototype.add = function(vector, out) { out = out || new Vec2(); out.x = this.x + vector.x; out.y = this.y + vector.y; return out; };
Vec2.prototype.sub = function (vector, out) { out = out || new Vec2(); out.x = this.x - vector.x; out.y = this.y - vector.y; return out; };
Vec2.prototype.magSqr = function () { return this.x * this.x + this.y * this.y; };
Vec2.prototype.mul = function (num, out) { out = out || new Vec2(); out.x = this.x * num; out.y = this.y * num; return out; };
Vec2.prototype.dot = function (vector) { return this.x * vector.x + this.y * vector.y; };
Vec2.prototype.project = function (vector) { return vector.mul(this.dot(vector) / vector.dot(vector)); };
function calcShortestPoint(x, y, x1, y1, x2, y2) { var op = new Vec2(x, y); var op1 = new Vec2(x1, y1); var op2 = new Vec2(x2, y2);
var p1p2 = op2.sub(op1); var p1p = op.sub(op1); var p2p = op.sub(op2); var proj_pp2_p1p2 = p2p.project(p1p2); var ot = op2.add(proj_pp2_p1p2); var pt = op.sub(ot); var tp1 = op1.sub(ot); var tp2 = op2.sub(ot); var len2_pp1 = p1p.magSqr(); var len2_pp2 = p2p.magSqr(); var len2_pt = pt.magSqr(); var pos = [op1, op2, ot][[len2_pp1, len2_pp2, len2_pt].indexOf(Math.min(len2_pp1, len2_pp2, len2_pt))]; if (tp1.magSqr() + tp2.magSqr() - p1p2.magSqr() > 0) { pos = [op1, op2][[len2_pp1, len2_pp2].indexOf(Math.min(len2_pp1, len2_pp2))]; } return pos; }
|