Game Development Reference
In-Depth Information
A.15
Intersection of a Sphere and a Plane
Detecting the static intersection of a sphere and a plane is relatively easy—
we simply compute the distance from the center of the sphere to the plane
by using Equation (9.14). If this distance is less than the radius of the
sphere, then the sphere intersects the plane. We can actually make a more
robust test, which classifies the sphere as being completely on the front,
completely on the back, or straddling the sphere. A code snippet is given
in Listing A.3.
/ /
Given
a
s p h e r e
and
plane ,
d e t e r m i n e
which
s i d e
o f
t h e
p l a n e
/ /
t h e
s p h e r e
i s
on .
/ /
/ /
R e t u r n
v a l u e s :
/ /
/ / < 0
Sphere
i s
c o m p l e t e l y
on
t h e
back
/ / > 0
Sphere
i s
c o m p l e t e l y
on
t h e
f r o n t
/ /
0
Sphere
s t r a d d l e s
p l a n e
i n t
c l a s s i f y S p h e r e P l a n e (
c o n s t
V e c t o r 3
&planeNormal ,
/ /
must
be
n o r m a l i z e d
f l o a t
planeD ,
/ /
p
planeNormal
=
planeD
c o n s t
V e c t o r 3
&s p h e r e C e n t e r ,
/ /
c e n t e r
o f
s p h e r e
f l o a t
s p h e r e R a d i u s
/ /
r a d i u s
o f
s p h e r e
)
{
/ /
Compute
d i s t a n c e
from
c e n t e r
o f
s p h e r e
t o
t h e
p l a n e
f l o a t
d
=
p l a n e N o r m a l
s p h e r e C e n t e r
planeD ;
/ /
C o m p l e t e l y
on
t h e
f r o n t
s i d e ?
i f
( d > =
s p h e r e R a d i u s )
{
r e t u r n
+ 1 ;
}
/ /
C o m p l e t e l y
on
t h e
back
s i d e ?
i f
( d < = s p h e r e R a d i u s )
{
r e t u r n
1;
}
/ /
Sphere
i n t e r s e c t s
t h e
p l a n e
r e t u r n
0 ;
}
Listing A.3
Determining which side of a plane a sphere is on
The dynamic situation is only slightly more complicated. We consider
the plane to be stationary, assigning all relative displacement to the sphere.
We define the plane in the usual manner by a normalized surface normal
n and distance value d such that all points p in the plane satisfy the equation
p n = d. The sphere is defined by its radius r and the initial position of
the center, c . The displacement of the sphere is given by a unit vector
d specifying the direction, and a distance l. As t varies from 0 to l, the
motion of the center of the sphere is given by the line equation c +t d . This
situation is shown, viewing the plane edge-on, in Figure A.13.
Search WWH ::




Custom Search