@@ -976,19 +976,27 @@ public boolean intersectsSphere(float r, PVector origin, PVector direction) {
976
976
objMatrix .mult (hit , hitInObjCoord );
977
977
PVector .sub (hitInObjCoord , origInObjCoord , dirInObjCoord );
978
978
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 ();
980
987
981
988
// The eye is inside the sphere
982
989
if (d <= r ) return true ;
983
990
984
- float p = PVector .dot (dirInObjCoord , origInObjCoord );
991
+ float p = PVector .dot (orig , dir );
985
992
986
993
// Check if sphere is in front of ray
987
994
if (p > 0 ) return false ;
988
995
989
996
// Check intersection of ray with sphere
990
997
float b = 2 * p ;
991
998
float c = d * d - r * r ;
999
+
992
1000
float det = b * b - 4 * c ;
993
1001
return det >= 0 ;
994
1002
}
@@ -1020,15 +1028,15 @@ public boolean intersectsBox(float w, float h, float d, PVector origin, PVector
1020
1028
objMatrix .mult (origin , origInObjCoord );
1021
1029
PVector .add (origin , direction , hit );
1022
1030
objMatrix .mult (hit , hitInObjCoord );
1023
-
1024
1031
PVector .sub (hitInObjCoord , origInObjCoord , dirInObjCoord );
1032
+
1025
1033
return lineIntersectsAABB (origInObjCoord , dirInObjCoord , w , h , d );
1026
1034
}
1027
1035
1028
1036
1029
1037
// Line intersection with an axis-aligned bounding box (AABB), calculated using the algorithm
1030
1038
// 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 ) {
1032
1040
float minx = -w /2 ;
1033
1041
float miny = -h /2 ;
1034
1042
float minz = -d /2 ;
0 commit comments