Browse Source

Merge pull request #14567 from yaoyao-cn/dev

add Vector2.cross method
Mr.doob 7 years ago
parent
commit
b27462e8ba
3 changed files with 25 additions and 2 deletions
  1. 6 0
      docs/api/math/Vector2.html
  2. 6 0
      src/math/Vector2.js
  3. 13 2
      test/unit/src/math/Vector2.tests.js

+ 6 - 0
docs/api/math/Vector2.html

@@ -176,6 +176,12 @@
 		Calculates the [link:https://en.wikipedia.org/wiki/Dot_product dot product] of this
 	  vector and [page:Vector2 v].
 		</p>
+        
+		<h3>[method:Float cross]( [param:Vector2 v] )</h3>
+		<p>
+		Calculates the [link:https://en.wikipedia.org/wiki/Cross_product cross product] of this
+	  vector and [page:Vector2 v]. Note that a 'cross-product' in 2D is not well-defined. This function computes a geometric cross-product often used in 2D graphics
+		</p>
 
 		<h3>[method:Boolean equals]( [param:Vector2 v] )</h3>
 		<p>Checks for strict equality of this vector and [page:Vector2 v].</p>

+ 6 - 0
src/math/Vector2.js

@@ -353,6 +353,12 @@ Object.assign( Vector2.prototype, {
 
 	},
 
+	cross: function ( v ) {
+
+		return this.x * v.y - this.y * v.x;
+
+	},
+
 	lengthSq: function () {
 
 		return this.x * this.x + this.y * this.y;

+ 13 - 2
test/unit/src/math/Vector2.tests.js

@@ -9,7 +9,8 @@ import { Matrix3 } from '../../../../src/math/Matrix3';
 import { BufferAttribute } from '../../../../src/core/BufferAttribute';
 import {
 	x,
-	y
+	y,
+	eps
 } from './Constants.tests';
 
 export default QUnit.module( 'Maths', () => {
@@ -306,6 +307,17 @@ export default QUnit.module( 'Maths', () => {
 
 		} );
 
+		QUnit.test( "cross", ( assert ) => {
+
+			var a = new Vector2( x, y );
+			var b = new Vector2( 2 * x, - y );
+			var answer = - 18;
+			var crossed = a.cross( b );
+
+			assert.ok( Math.abs( answer - crossed ) <= eps, "Check cross" );
+
+		} );
+
 		QUnit.todo( "lengthSq", ( assert ) => {
 
 			assert.ok( false, "everything's gonna be alright" );
@@ -337,7 +349,6 @@ export default QUnit.module( 'Maths', () => {
 
 			var a = new Vector2( x, 0 );
 			var b = new Vector2( 0, - y );
-			var c = new Vector2();
 
 			a.normalize();
 			assert.ok( a.length() == 1, "Passed!" );