diff --git a/binaries/data/mods/public/globalscripts/vector.js b/binaries/data/mods/public/globalscripts/vector.js index e9c23a5433..9bac1ed091 100644 --- a/binaries/data/mods/public/globalscripts/vector.js +++ b/binaries/data/mods/public/globalscripts/vector.js @@ -91,12 +91,29 @@ Vector2D.prototype.rotate = function(a) // // These methods serve to get numeric info on the vector, they don't modify the vector +/** + * Return the vector that forms a right angle with this one. + */ +Vector2D.prototype.perpendicular = function() +{ + return new Vector2D(-this.y, this.x); +}; + +/** + * Computes the scalar product of the two vectors. + * Geometrically, this is the product of the length of the two vectors and the cosine of the angle between them. + * If the vectors are orthogonal, the product is zero. + */ Vector2D.prototype.dot = function(v) { return this.x * v.x + this.y * v.y; }; -// get the non-zero coordinate of the vector cross +/** + * Computes the non-zero coordinate of the cross product of the two vectors. + * Geometrically, the cross of the vectors is the 3D vector perpendicular to the two 2D vectors. + * This returned length of that vector equals the area of the parallelogram that the vectors span. + */ Vector2D.prototype.cross = function(v) { return this.x * v.y - this.y * v.x; @@ -259,6 +276,18 @@ Vector3D.prototype.dot = function(v) return this.x * v.x + this.y * v.y + this.z * v.z; }; +/** + * Returns a vector perpendicular to the two given vectors. + * The length of the returned vector corresponds to the area of the parallelogram with the vectors for sides. + */ +Vector3D.prototype.cross = function(v) +{ + return new Vector3D( + this.y * v.z - this.z * v.y, + this.z * v.x - this.x * v.z, + this.x * v.y - this.y * v.x); +}; + Vector3D.prototype.lengthSquared = function() { return this.dot(this); diff --git a/binaries/data/mods/public/simulation/components/tests/test_Vector.js b/binaries/data/mods/public/simulation/components/tests/test_Vector.js index c70e35bd55..d70f9a5439 100644 --- a/binaries/data/mods/public/simulation/components/tests/test_Vector.js +++ b/binaries/data/mods/public/simulation/components/tests/test_Vector.js @@ -86,6 +86,14 @@ var brokenVector = { TS_ASSERT_EQUALS(v5.x, v6.x); TS_ASSERT_EQUALS(v5.y, v6.y); TS_ASSERT(Math.abs(v5.dot(v6.rotate(Math.PI / 2))) < epsilon); + + let v7 = new Vector2D(4, 5).perpendicular(); + TS_ASSERT_EQUALS(v7.x, -5); + TS_ASSERT_EQUALS(v7.y, 4); + + let v8 = new Vector2D(0, 0).perpendicular(); + TS_ASSERT_EQUALS(v8.x, 0); + TS_ASSERT_EQUALS(v8.y, 0); } // Test Vector3D @@ -106,4 +114,9 @@ var brokenVector = { TS_ASSERT_EQUALS(v3.x, v4.x); TS_ASSERT_EQUALS(v3.y, v4.y); TS_ASSERT_EQUALS(v3.z, v4.z); + + let v5 = new Vector3D(1, 2, 3).cross(new Vector3D(4, 5, 6)); + TS_ASSERT_EQUALS(v5.x, -3); + TS_ASSERT_EQUALS(v5.y, 6); + TS_ASSERT_EQUALS(v5.z, -3); }