@@ -976,19 +976,27 @@ public boolean intersectsSphere(float r, PVector origin, PVector direction) {
976976 objMatrix .mult (hit , hitInObjCoord );
977977 PVector .sub (hitInObjCoord , origInObjCoord , dirInObjCoord );
978978
979- float d = origInObjCoord .mag ();
979+ return lineIntersectsSphere (origInObjCoord , dirInObjCoord , r );
980+ }
981+
982+
983+ // Line-sphere intersecton algorithm as described in:
984+ // http://paulbourke.net/geometry/circlesphere/
985+ private boolean lineIntersectsSphere (PVector orig , PVector dir , float r ) {
986+ float d = orig .mag ();
980987
981988 // The eye is inside the sphere
982989 if (d <= r ) return true ;
983990
984- float p = PVector .dot (dirInObjCoord , origInObjCoord );
991+ float p = PVector .dot (orig , dir );
985992
986993 // Check if sphere is in front of ray
987994 if (p > 0 ) return false ;
988995
989996 // Check intersection of ray with sphere
990997 float b = 2 * p ;
991998 float c = d * d - r * r ;
999+
9921000 float det = b * b - 4 * c ;
9931001 return det >= 0 ;
9941002 }
@@ -1020,15 +1028,15 @@ public boolean intersectsBox(float w, float h, float d, PVector origin, PVector
10201028 objMatrix .mult (origin , origInObjCoord );
10211029 PVector .add (origin , direction , hit );
10221030 objMatrix .mult (hit , hitInObjCoord );
1023-
10241031 PVector .sub (hitInObjCoord , origInObjCoord , dirInObjCoord );
1032+
10251033 return lineIntersectsAABB (origInObjCoord , dirInObjCoord , w , h , d );
10261034 }
10271035
10281036
10291037 // Line intersection with an axis-aligned bounding box (AABB), calculated using the algorithm
10301038 // from Amy William et al: http:// dl.acm.org/citation.cfm?id=1198748
1031- protected boolean lineIntersectsAABB (PVector orig , PVector dir , float w , float h , float d ) {
1039+ private boolean lineIntersectsAABB (PVector orig , PVector dir , float w , float h , float d ) {
10321040 float minx = -w /2 ;
10331041 float miny = -h /2 ;
10341042 float minz = -d /2 ;
0 commit comments