Browse Source

add Vector3.project, Vector3.ortho and Vector3.reflect based on request by #3009

Ben Houston 12 years ago
parent
commit
f4e081c9e8
2 changed files with 87 additions and 0 deletions
  1. 36 0
      src/math/Vector3.js
  2. 51 0
      test/unit/math/Vector3.js

+ 36 - 0
src/math/Vector3.js

@@ -520,6 +520,42 @@ THREE.extend( THREE.Vector3.prototype, {
 
 	},
 
+
+	project: function( normal ) {
+
+		var cosTheta = this.dot( normal );
+		return this.copy( normal ).multiplyScalar( cosTheta );
+
+	},
+	
+	ortho: function () {
+
+		var v1 = new THREE.Vector3();
+
+		return function( normal ) {
+
+			v1.copy( this ).project( normal );
+
+			return this.sub( v1 );
+
+		}
+
+	}(),
+
+	reflect: function () {
+
+		var v1 = new THREE.Vector3();
+
+		return function ( normal ) {
+
+		    v1.copy( this ).ortho( normal ).multiplyScalar( -2 );
+
+		    return this.add( v1 );
+
+		}
+
+	}(),
+
 	angleTo: function ( v ) {
 
 		return Math.acos( this.dot( v ) / this.length() / v.length() );

+ 51 - 0
test/unit/math/Vector3.js

@@ -239,6 +239,57 @@ test( "setLength", function() {
 
 });
 
+test( "project", function() {
+	var a = new THREE.Vector3( 1, 0, 0 );
+	var b = new THREE.Vector3();
+	var normal = new THREE.Vector3( 1, 0, 0 );
+
+	ok( b.copy( a ).project( normal ).equals( new THREE.Vector3( 1, 0, 0 ) ), "Passed!" );
+
+	a.set( 0, 1, 0 );
+	ok( b.copy( a ).project( normal ).equals( new THREE.Vector3( 0, 0, 0 ) ), "Passed!" );
+
+	a.set( 0, 0, -1 );
+	ok( b.copy( a ).project( normal ).equals( new THREE.Vector3( 0, 0, 0 ) ), "Passed!" );
+
+	a.set( -1, 0, 0 );
+	ok( b.copy( a ).project( normal ).equals( new THREE.Vector3( -1, 0, 0 ) ), "Passed!" );
+
+});
+
+test( "ortho", function() {
+	var a = new THREE.Vector3( 1, 0, 0 );
+	var b = new THREE.Vector3();
+	var normal = new THREE.Vector3( 1, 0, 0 );
+
+	ok( b.copy( a ).ortho( normal ).equals( new THREE.Vector3( 0, 0, 0 ) ), "Passed!" );
+
+	a.set( 0, 1, 0 );
+	ok( b.copy( a ).ortho( normal ).equals( new THREE.Vector3( 0, 1, 0 ) ), "Passed!" );
+
+	a.set( 0, 0, -1 );
+	ok( b.copy( a ).ortho( normal ).equals( new THREE.Vector3( 0, 0, -1 ) ), "Passed!" );
+
+	a.set( -1, 0, 0 );
+	ok( b.copy( a ).ortho( normal ).equals( new THREE.Vector3( 0, 0, 0 ) ), "Passed!" );
+
+});
+
+test( "reflect", function() {
+	var a = new THREE.Vector3( 1, 0, 0 );
+	var normal = new THREE.Vector3( 1, 0, 0 );
+	var b = new THREE.Vector3( 0, 0, 0 );
+
+	ok( b.copy( a ).reflect( normal ).equals( new THREE.Vector3( 1, 0, 0 ) ), "Passed!" );
+
+	a.set( 1, -1, 0 );
+	ok( b.copy( a ).reflect( normal ).equals( new THREE.Vector3( 1, 1, 0 ) ), "Passed!" );
+
+	a.set( 1, -1, 0 );
+	normal.set( 0, -1, 0 )
+	ok( b.copy( a ).reflect(  normal ).equals( new THREE.Vector3( -1, -1, 0 ) ), "Passed!" );
+});
+
 test( "lerp/clone", function() {
 	var a = new THREE.Vector3( x, 0, z );
 	var b = new THREE.Vector3( 0, -y, 0 );