浏览代码

Improved implementation and unit test for Vector3.angleTo to account for numerical problems outside of full [-1,1] range.

Drew Noakes 12 年之前
父节点
当前提交
e4a451a8a0
共有 2 个文件被更改,包括 14 次插入2 次删除
  1. 11 1
      src/math/Vector3.js
  2. 3 1
      test/unit/math/Vector3.js

+ 11 - 1
src/math/Vector3.js

@@ -564,7 +564,17 @@ THREE.extend( THREE.Vector3.prototype, {
 
 
 	angleTo: function ( v ) {
 	angleTo: function ( v ) {
 
 
-		return Math.acos( Math.min ( 1, this.dot( v ) / this.length() / v.length() ) );
+		// clamp, to handle numerical problems
+
+		function clamp( x ) {
+
+			return Math.min( Math.max( x, -1 ), 1 );
+
+		}
+
+		var theta = this.dot( v ) / ( this.length() * v.length() );
+
+		return Math.acos( clamp ( theta ) );
 
 
 	},
 	},
 
 

+ 3 - 1
test/unit/math/Vector3.js

@@ -292,8 +292,10 @@ test( "reflect", function() {
 
 
 test( "angleTo", function() {
 test( "angleTo", function() {
 	var a = new THREE.Vector3( 0, -0.18851655680720186, 0.9820700116639124 );
 	var a = new THREE.Vector3( 0, -0.18851655680720186, 0.9820700116639124 );
+	var b = new THREE.Vector3( 0, 0.18851655680720186, -0.9820700116639124 );
 
 
-	equal( a.angleTo( a ),  0 );
+	equal( a.angleTo( a ), 0 );
+	equal( a.angleTo( b ), Math.PI );
 
 
 	var x = new THREE.Vector3( 1, 0, 0 );
 	var x = new THREE.Vector3( 1, 0, 0 );
 	var y = new THREE.Vector3( 0, 1, 0 );
 	var y = new THREE.Vector3( 0, 1, 0 );