Add Vector3D crossproduct and Vector2D perpendicular function.

Describe geometric features of the two cross- and dot-product functions.

This was SVN commit r20428.
This commit is contained in:
elexis 2017-11-09 19:04:39 +00:00
parent 8ee600b979
commit b3dbcc457b
2 changed files with 43 additions and 1 deletions

View file

@ -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);

View file

@ -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);
}