Explorar o código

Make intersectSphere method closure, and always return point in front of ray

erichlof %!s(int64=11) %!d(string=hai) anos
pai
achega
2739a972f7
Modificáronse 1 ficheiros con 28 adicións e 27 borrados
  1. 28 27
      src/math/Ray.js

+ 28 - 27
src/math/Ray.js

@@ -217,44 +217,45 @@ THREE.Ray.prototype = {
 
 	},
 	
-	intersectSphere: function ( sphere, optionalTarget ) {
+	intersectSphere: function () {
 
 		// from http://www.scratchapixel.com/lessons/3d-basic-lessons/lesson-7-intersecting-simple-shapes/ray-sphere-intersection/
-		var L = new THREE.Vector3();
-		var radius = sphere.radius;
-		var radius2 = radius * radius;
-
-		L.subVectors( sphere.center, this.origin );
-
-		var tca = L.dot( this.direction );
+		
+		var v1 = new THREE.Vector3();
+		
+		return function ( sphere, optionalTarget ) {
 
-		if ( tca < 0 ) {
+			v1.subVectors( sphere.center, this.origin );
 
-			return null;
+			var tca = v1.dot( this.direction );
 
-		}
+			if ( tca < 0 ) return null;
 
-		var d2 = L.dot( L ) - tca * tca;
+			var d2 = v1.dot( v1 ) - tca * tca;
 
-		if ( d2 > radius2 ) {
+			var radius2 = sphere.radius * sphere.radius;
+			
+			if ( d2 > radius2 ) return null;
 
-			return null;
+			var thc = Math.sqrt( radius2 - d2 );
+			
+			// t0 = first intersect point - entrance on front of sphere
+			var t0 = tca - thc;
 
+			// t1 = second intersect point - exit point on back of sphere
+			var t1 = tca + thc;
+		
+			// test to see if t0 is behind the ray:
+			// if it is, the ray is inside the sphere, so return the second exit point scaled by t1,
+			// in order to always return an intersect point that is in front of the ray.
+			if (t0 < 0) return this.at( t1, optionalTarget );
+
+			// else t0 is in front of the ray, so return the first collision point scaled by t0 
+			return this.at( t0, optionalTarget );
+			
 		}
-
-		var thc = Math.sqrt( radius2 - d2 );
-		// t0 = first collision point entrance on front of sphere
-		var t0 = tca - thc;
-
-		// t1 = exit point on back of sphere.  Rarely needed, so it is commented out
-		// var t1 = tca + thc; 
-
-		// Now return the THREE.Vector3() location (collision point) of this Ray,
-		//   scaled by amount t0 along Ray.direction  
-		// This collision point will always be located somewhere on the sphere
-		return this.at( t0, optionalTarget );
 	
-	},
+	}(),
 
 	isIntersectionPlane: function ( plane ) {